Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1061
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1061 ! www 4: # $Id: lonnet.pm,v 1.1060 2010/03/26 00:47:25 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.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
199: my ($dom,$lonhost) = @_;
200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
214: my $cachetime = 24*3600;
215: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
216: if (defined($cached)) {
217: return $loncaparev;
218: } else {
219: my $loncaparev = &reply('serverloncaparev',$lonhost);
220: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
221: }
222: }
223: }
224:
1.1 albertel 225: # -------------------------------------------------- Non-critical communication
226: sub subreply {
227: my ($cmd,$server)=@_;
1.838 albertel 228: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 229: #
230: # With loncnew process trimming, there's a timing hole between lonc server
231: # process exit and the master server picking up the listen on the AF_UNIX
232: # socket. In that time interval, a lock file will exist:
233:
234: my $lockfile=$peerfile.".lock";
235: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
236: sleep(1);
237: }
238: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 239: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 240: #
1.550 foxr 241: # We'll give the connection a few tries before abandoning it. If
242: # connection is not possible, we'll con_lost back to the client.
243: #
244: my $client;
245: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
246: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
247: Type => SOCK_STREAM,
248: Timeout => 10);
1.869 albertel 249: if ($client) {
1.550 foxr 250: last; # Connected!
1.850 albertel 251: } else {
1.853 albertel 252: &create_connection(&hostname($server),$server);
1.550 foxr 253: }
1.850 albertel 254: sleep(1); # Try again later if failed connection.
1.550 foxr 255: }
256: my $answer;
257: if ($client) {
1.704 albertel 258: print $client "sethost:$server:$cmd\n";
1.550 foxr 259: $answer=<$client>;
260: if (!$answer) { $answer="con_lost"; }
261: chomp($answer);
262: } else {
263: $answer = 'con_lost'; # Failed connection.
264: }
1.1 albertel 265: return $answer;
266: }
267:
268: sub reply {
269: my ($cmd,$server)=@_;
1.838 albertel 270: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 271: my $answer=subreply($cmd,$server);
1.65 www 272: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 273: &logthis("<font color=\"blue\">WARNING:".
1.12 www 274: " $cmd to $server returned $answer</font>");
275: }
1.1 albertel 276: return $answer;
277: }
278:
279: # ----------------------------------------------------------- Send USR1 to lonc
280:
281: sub reconlonc {
1.891 albertel 282: my ($lonid) = @_;
283: my $hostname = &hostname($lonid);
284: if ($lonid) {
285: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
286: if ($hostname && -e $peerfile) {
287: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
288: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
289: Type => SOCK_STREAM,
290: Timeout => 10);
291: if ($client) {
292: print $client ("reset_retries\n");
293: my $answer=<$client>;
294: #reset just this one.
295: }
296: }
297: return;
298: }
299:
1.836 www 300: &logthis("Trying to reconnect lonc");
1.1 albertel 301: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 302: if (open(my $fh,"<$loncfile")) {
1.1 albertel 303: my $loncpid=<$fh>;
304: chomp($loncpid);
305: if (kill 0 => $loncpid) {
306: &logthis("lonc at pid $loncpid responding, sending USR1");
307: kill USR1 => $loncpid;
308: sleep 1;
1.836 www 309: } else {
1.12 www 310: &logthis(
1.672 albertel 311: "<font color=\"blue\">WARNING:".
1.12 www 312: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 313: }
314: } else {
1.836 www 315: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 316: }
317: }
318:
319: # ------------------------------------------------------ Critical communication
1.12 www 320:
1.1 albertel 321: sub critical {
322: my ($cmd,$server)=@_;
1.838 albertel 323: unless (&hostname($server)) {
1.672 albertel 324: &logthis("<font color=\"blue\">WARNING:".
1.89 www 325: " Critical message to unknown server ($server)</font>");
326: return 'no_such_host';
327: }
1.1 albertel 328: my $answer=reply($cmd,$server);
329: if ($answer eq 'con_lost') {
330: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 331: my $answer=reply($cmd,$server);
1.1 albertel 332: if ($answer eq 'con_lost') {
333: my $now=time;
334: my $middlename=$cmd;
1.5 www 335: $middlename=substr($middlename,0,16);
1.1 albertel 336: $middlename=~s/\W//g;
337: my $dfilename=
1.305 www 338: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
339: $dumpcount++;
1.1 albertel 340: {
1.448 albertel 341: my $dfh;
342: if (open($dfh,">$dfilename")) {
343: print $dfh "$cmd\n";
344: close($dfh);
345: }
1.1 albertel 346: }
347: sleep 2;
348: my $wcmd='';
349: {
1.448 albertel 350: my $dfh;
351: if (open($dfh,"<$dfilename")) {
352: $wcmd=<$dfh>;
353: close($dfh);
354: }
1.1 albertel 355: }
356: chomp($wcmd);
1.7 www 357: if ($wcmd eq $cmd) {
1.672 albertel 358: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 359: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 360: &logperm("D:$server:$cmd");
361: return 'con_delayed';
362: } else {
1.672 albertel 363: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 364: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 365: &logperm("F:$server:$cmd");
366: return 'con_failed';
367: }
368: }
369: }
370: return $answer;
1.405 albertel 371: }
372:
1.755 albertel 373: # ------------------------------------------- check if return value is an error
374:
375: sub error {
376: my ($result) = @_;
1.756 albertel 377: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 378: if ($2 == 2) { return undef; }
379: return $1;
380: }
381: return undef;
382: }
383:
1.783 albertel 384: sub convert_and_load_session_env {
385: my ($lonidsdir,$handle)=@_;
386: my @profile;
387: {
1.917 albertel 388: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
389: if (!$opened) {
1.915 albertel 390: return 0;
391: }
1.783 albertel 392: flock($idf,LOCK_SH);
393: @profile=<$idf>;
394: close($idf);
395: }
396: my %temp_env;
397: foreach my $line (@profile) {
1.786 albertel 398: if ($line !~ m/=/) {
399: return 0;
400: }
1.783 albertel 401: chomp($line);
402: my ($envname,$envvalue)=split(/=/,$line,2);
403: $temp_env{&unescape($envname)} = &unescape($envvalue);
404: }
405: unlink("$lonidsdir/$handle.id");
406: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
407: 0640)) {
408: %disk_env = %temp_env;
409: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
410: untie(%disk_env);
411: }
1.786 albertel 412: return 1;
1.783 albertel 413: }
414:
1.374 www 415: # ------------------------------------------- Transfer profile into environment
1.780 albertel 416: my $env_loaded;
417: sub transfer_profile_to_env {
1.788 albertel 418: my ($lonidsdir,$handle,$force_transfer) = @_;
419: if (!$force_transfer && $env_loaded) { return; }
1.374 www 420:
1.720 albertel 421: if (!defined($lonidsdir)) {
422: $lonidsdir = $perlvar{'lonIDsDir'};
423: }
424: if (!defined($handle)) {
425: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
426: }
427:
1.786 albertel 428: my $convert;
429: {
1.917 albertel 430: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
431: if (!$opened) {
1.915 albertel 432: return;
433: }
1.786 albertel 434: flock($idf,LOCK_SH);
435: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
436: &GDBM_READER(),0640)) {
437: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
438: untie(%disk_env);
439: } else {
440: $convert = 1;
441: }
442: }
443: if ($convert) {
444: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
445: &logthis("Failed to load session, or convert session.");
446: }
1.374 www 447: }
1.783 albertel 448:
1.786 albertel 449: my %remove;
1.783 albertel 450: while ( my $envname = each(%env) ) {
1.433 matthew 451: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
452: if ($time < time-300) {
1.783 albertel 453: $remove{$key}++;
1.433 matthew 454: }
455: }
456: }
1.783 albertel 457:
1.619 albertel 458: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 459: $env_loaded=1;
1.783 albertel 460: foreach my $expired_key (keys(%remove)) {
1.433 matthew 461: &delenv($expired_key);
1.374 www 462: }
1.1 albertel 463: }
464:
1.916 albertel 465: # ---------------------------------------------------- Check for valid session
466: sub check_for_valid_session {
467: my ($r) = @_;
468: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
469: my $lonid=$cookies{'lonID'};
470: return undef if (!$lonid);
471:
472: my $handle=&LONCAPA::clean_handle($lonid->value);
473: my $lonidsdir=$r->dir_config('lonIDsDir');
474: return undef if (!-e "$lonidsdir/$handle.id");
475:
1.917 albertel 476: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
477: return undef if (!$opened);
1.916 albertel 478:
479: flock($idf,LOCK_SH);
480: my %disk_env;
481: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
482: &GDBM_READER(),0640)) {
483: return undef;
484: }
485:
486: if (!defined($disk_env{'user.name'})
487: || !defined($disk_env{'user.domain'})) {
488: return undef;
489: }
490: return $handle;
491: }
492:
1.830 albertel 493: sub timed_flock {
494: my ($file,$lock_type) = @_;
495: my $failed=0;
496: eval {
497: local $SIG{__DIE__}='DEFAULT';
498: local $SIG{ALRM}=sub {
499: $failed=1;
500: die("failed lock");
501: };
502: alarm(13);
503: flock($file,$lock_type);
504: alarm(0);
505: };
506: if ($failed) {
507: return undef;
508: } else {
509: return 1;
510: }
511: }
512:
1.5 www 513: # ---------------------------------------------------------- Append Environment
514:
515: sub appenv {
1.949 raeburn 516: my ($newenv,$roles) = @_;
517: if (ref($newenv) eq 'HASH') {
518: foreach my $key (keys(%{$newenv})) {
519: my $refused = 0;
520: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
521: $refused = 1;
522: if (ref($roles) eq 'ARRAY') {
523: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
524: if (grep(/^\Q$role\E$/,@{$roles})) {
525: $refused = 0;
526: }
527: }
528: }
529: if ($refused) {
530: &logthis("<font color=\"blue\">WARNING: ".
531: "Attempt to modify environment ".$key." to ".$newenv->{$key}
532: .'</font>');
533: delete($newenv->{$key});
534: } else {
535: $env{$key}=$newenv->{$key};
536: }
537: }
538: my $opened = open(my $env_file,'+<',$env{'user.environment'});
539: if ($opened
540: && &timed_flock($env_file,LOCK_EX)
541: &&
542: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
543: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
544: while (my ($key,$value) = each(%{$newenv})) {
545: $disk_env{$key} = $value;
546: }
547: untie(%disk_env);
1.35 www 548: }
1.191 harris41 549: }
1.56 www 550: return 'ok';
551: }
552: # ----------------------------------------------------- Delete from Environment
553:
554: sub delenv {
1.987 raeburn 555: my ($delthis,$regexp) = @_;
1.56 www 556: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 557: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 558: "Attempt to delete from environment ".$delthis);
559: return 'error';
560: }
1.917 albertel 561: my $opened = open(my $env_file,'+<',$env{'user.environment'});
562: if ($opened
1.915 albertel 563: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 564: &&
565: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
566: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 567: foreach my $key (keys(%disk_env)) {
1.987 raeburn 568: if ($regexp) {
569: if ($key=~/^$delthis/) {
570: delete($env{$key});
571: delete($disk_env{$key});
572: }
573: } else {
574: if ($key=~/^\Q$delthis\E/) {
575: delete($env{$key});
576: delete($disk_env{$key});
577: }
578: }
1.448 albertel 579: }
1.783 albertel 580: untie(%disk_env);
1.5 www 581: }
582: return 'ok';
1.369 albertel 583: }
584:
1.790 albertel 585: sub get_env_multiple {
586: my ($name) = @_;
587: my @values;
588: if (defined($env{$name})) {
589: # exists is it an array
590: if (ref($env{$name})) {
591: @values=@{ $env{$name} };
592: } else {
593: $values[0]=$env{$name};
594: }
595: }
596: return(@values);
597: }
598:
1.958 www 599: # ------------------------------------------------------------------- Locking
600:
601: sub set_lock {
602: my ($text)=@_;
603: $locknum++;
604: my $id=$$.'-'.$locknum;
605: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
606: 'session.lock.'.$id => $text});
607: return $id;
608: }
609:
610: sub get_locks {
611: my $num=0;
612: my %texts=();
613: foreach my $lock (split(/\,/,$env{'session.locks'})) {
614: if ($lock=~/\w/) {
615: $num++;
616: $texts{$lock}=$env{'session.lock.'.$lock};
617: }
618: }
619: return ($num,%texts);
620: }
621:
622: sub remove_lock {
623: my ($id)=@_;
624: my $newlocks='';
625: foreach my $lock (split(/\,/,$env{'session.locks'})) {
626: if (($lock=~/\w/) && ($lock ne $id)) {
627: $newlocks.=','.$lock;
628: }
629: }
630: &appenv({'session.locks' => $newlocks});
631: &delenv('session.lock.'.$id);
632: }
633:
634: sub remove_all_locks {
635: my $activelocks=$env{'session.locks'};
636: foreach my $lock (split(/\,/,$env{'session.locks'})) {
637: if ($lock=~/\w/) {
638: &remove_lock($lock);
639: }
640: }
641: }
642:
643:
1.369 albertel 644: # ------------------------------------------ Find out current server userload
645: sub userload {
646: my $numusers=0;
647: {
648: opendir(LONIDS,$perlvar{'lonIDsDir'});
649: my $filename;
650: my $curtime=time;
651: while ($filename=readdir(LONIDS)) {
1.925 albertel 652: next if ($filename eq '.' || $filename eq '..');
653: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 654: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 655: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 656: }
657: closedir(LONIDS);
658: }
659: my $userloadpercent=0;
660: my $maxuserload=$perlvar{'lonUserLoadLim'};
661: if ($maxuserload) {
1.371 albertel 662: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 663: }
1.372 albertel 664: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 665: return $userloadpercent;
1.283 www 666: }
667:
1.1 albertel 668: # ------------------------------ Find server with least workload from spare.tab
1.11 www 669:
1.1 albertel 670: sub spareserver {
1.670 albertel 671: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 672: my $spare_server;
1.370 albertel 673: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 674: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
675: : $userloadpercent;
676:
677: foreach my $try_server (@{ $spareid{'primary'} }) {
678: ($spare_server, $lowest_load) =
679: &compare_server_load($try_server, $spare_server, $lowest_load);
680: }
681:
682: my $found_server = ($spare_server ne '' && $lowest_load < 100);
683:
684: if (!$found_server) {
685: foreach my $try_server (@{ $spareid{'default'} }) {
686: ($spare_server, $lowest_load) =
687: &compare_server_load($try_server, $spare_server, $lowest_load);
688: }
689: }
690:
691: if (!$want_server_name) {
1.968 raeburn 692: my $protocol = 'http';
693: if ($protocol{$spare_server} eq 'https') {
694: $protocol = $protocol{$spare_server};
695: }
1.1001 raeburn 696: if (defined($spare_server)) {
697: my $hostname = &hostname($spare_server);
698: if (defined($hostname)) {
699: $spare_server = $protocol.'://'.$hostname;
700: }
701: }
1.784 albertel 702: }
703: return $spare_server;
704: }
705:
706: sub compare_server_load {
707: my ($try_server, $spare_server, $lowest_load) = @_;
708:
709: my $loadans = &reply('load', $try_server);
710: my $userloadans = &reply('userload',$try_server);
711:
712: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
713: next; #didn't get a number from the server
714: }
715:
716: my $load;
717: if ($loadans =~ /\d/) {
718: if ($userloadans =~ /\d/) {
719: #both are numbers, pick the bigger one
720: $load = ($loadans > $userloadans) ? $loadans
721: : $userloadans;
1.411 albertel 722: } else {
1.784 albertel 723: $load = $loadans;
1.411 albertel 724: }
1.784 albertel 725: } else {
726: $load = $userloadans;
727: }
728:
729: if (($load =~ /\d/) && ($load < $lowest_load)) {
730: $spare_server = $try_server;
731: $lowest_load = $load;
1.370 albertel 732: }
1.784 albertel 733: return ($spare_server,$lowest_load);
1.202 matthew 734: }
1.914 albertel 735:
736: # --------------------------- ask offload servers if user already has a session
737: sub find_existing_session {
738: my ($udom,$uname) = @_;
739: foreach my $try_server (@{ $spareid{'primary'} },
740: @{ $spareid{'default'} }) {
741: return $try_server if (&has_user_session($try_server, $udom, $uname));
742: }
743: return;
744: }
745:
746: # -------------------------------- ask if server already has a session for user
747: sub has_user_session {
748: my ($lonid,$udom,$uname) = @_;
749: my $result = &reply(join(':','userhassession',
750: map {&escape($_)} ($udom,$uname)),$lonid);
751: return 1 if ($result eq 'ok');
752:
753: return 0;
754: }
755:
1.202 matthew 756: # --------------------------------------------- Try to change a user's password
757:
758: sub changepass {
1.799 raeburn 759: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 760: $currentpass = &escape($currentpass);
761: $newpass = &escape($newpass);
1.1030 raeburn 762: my $lonhost = $perlvar{'lonHostID'};
763: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 764: $server);
765: if (! $answer) {
766: &logthis("No reply on password change request to $server ".
767: "by $uname in domain $udom.");
768: } elsif ($answer =~ "^ok") {
769: &logthis("$uname in $udom successfully changed their password ".
770: "on $server.");
771: } elsif ($answer =~ "^pwchange_failure") {
772: &logthis("$uname in $udom was unable to change their password ".
773: "on $server. The action was blocked by either lcpasswd ".
774: "or pwchange");
775: } elsif ($answer =~ "^non_authorized") {
776: &logthis("$uname in $udom did not get their password correct when ".
777: "attempting to change it on $server.");
778: } elsif ($answer =~ "^auth_mode_error") {
779: &logthis("$uname in $udom attempted to change their password despite ".
780: "not being locally or internally authenticated on $server.");
781: } elsif ($answer =~ "^unknown_user") {
782: &logthis("$uname in $udom attempted to change their password ".
783: "on $server but were unable to because $server is not ".
784: "their home server.");
785: } elsif ($answer =~ "^refused") {
786: &logthis("$server refused to change $uname in $udom password because ".
787: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 788: } elsif ($answer =~ "invalid_client") {
789: &logthis("$server refused to change $uname in $udom password because ".
790: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 791: }
792: return $answer;
1.1 albertel 793: }
794:
1.169 harris41 795: # ----------------------- Try to determine user's current authentication scheme
796:
797: sub queryauthenticate {
798: my ($uname,$udom)=@_;
1.456 albertel 799: my $uhome=&homeserver($uname,$udom);
800: if (!$uhome) {
801: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
802: return 'no_host';
803: }
804: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
805: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
806: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 807: }
1.456 albertel 808: return $answer;
1.169 harris41 809: }
810:
1.1 albertel 811: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 812:
1.1 albertel 813: sub authenticate {
1.952 raeburn 814: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 815: $upass=&escape($upass);
816: $uname= &LONCAPA::clean_username($uname);
1.836 www 817: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 818: my $newhome;
1.836 www 819: if ((!$uhome) || ($uhome eq 'no_host')) {
820: # Maybe the machine was offline and only re-appeared again recently?
821: &reconlonc();
822: # One more
1.952 raeburn 823: $uhome=&homeserver($uname,$udom,1);
824: if (($uhome eq 'no_host') && $checkdefauth) {
825: if (defined(&domain($udom,'primary'))) {
826: $newhome=&domain($udom,'primary');
827: }
828: if ($newhome ne '') {
829: $uhome = $newhome;
830: }
831: }
1.836 www 832: if ((!$uhome) || ($uhome eq 'no_host')) {
833: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 834: return 'no_host';
835: }
1.1 albertel 836: }
1.952 raeburn 837: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 838: if ($answer eq 'authorized') {
1.952 raeburn 839: if ($newhome) {
840: &logthis("User $uname at $udom authorized by $uhome, but needs account");
841: return 'no_account_on_host';
842: } else {
843: &logthis("User $uname at $udom authorized by $uhome");
844: return $uhome;
845: }
1.471 albertel 846: }
847: if ($answer eq 'non_authorized') {
848: &logthis("User $uname at $udom rejected by $uhome");
849: return 'no_host';
1.9 www 850: }
1.471 albertel 851: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 852: return 'no_host';
853: }
854:
855: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 856:
1.599 albertel 857: my %homecache;
1.1 albertel 858: sub homeserver {
1.230 stredwic 859: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 860: my $index="$uname:$udom";
1.426 albertel 861:
1.599 albertel 862: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 863:
864: my %servers = &get_servers($udom,'library');
865: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 866: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 867: exists($badServerCache{$tryserver}));
1.841 albertel 868:
869: my $answer=reply("home:$udom:$uname",$tryserver);
870: if ($answer eq 'found') {
871: delete($badServerCache{$tryserver});
872: return $homecache{$index}=$tryserver;
873: } elsif ($answer eq 'no_host') {
874: $badServerCache{$tryserver}=1;
875: }
1.1 albertel 876: }
877: return 'no_host';
1.70 www 878: }
879:
880: # ------------------------------------- Find the usernames behind a list of IDs
881:
882: sub idget {
883: my ($udom,@ids)=@_;
884: my %returnhash=();
885:
1.841 albertel 886: my %servers = &get_servers($udom,'library');
887: foreach my $tryserver (keys(%servers)) {
888: my $idlist=join('&',@ids);
889: $idlist=~tr/A-Z/a-z/;
890: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
891: my @answer=();
892: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
893: @answer=split(/\&/,$reply);
894: } ;
895: my $i;
896: for ($i=0;$i<=$#ids;$i++) {
897: if ($answer[$i]) {
898: $returnhash{$ids[$i]}=$answer[$i];
899: }
900: }
901: }
1.70 www 902: return %returnhash;
903: }
904:
905: # ------------------------------------- Find the IDs behind a list of usernames
906:
907: sub idrget {
908: my ($udom,@unames)=@_;
909: my %returnhash=();
1.800 albertel 910: foreach my $uname (@unames) {
911: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 912: }
1.70 www 913: return %returnhash;
914: }
915:
916: # ------------------------------- Store away a list of names and associated IDs
917:
918: sub idput {
919: my ($udom,%ids)=@_;
920: my %servers=();
1.800 albertel 921: foreach my $uname (keys(%ids)) {
922: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
923: my $uhom=&homeserver($uname,$udom);
1.70 www 924: if ($uhom ne 'no_host') {
1.800 albertel 925: my $id=&escape($ids{$uname});
1.70 www 926: $id=~tr/A-Z/a-z/;
1.800 albertel 927: my $esc_unam=&escape($uname);
1.70 www 928: if ($servers{$uhom}) {
1.800 albertel 929: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 930: } else {
1.800 albertel 931: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 932: }
933: }
1.191 harris41 934: }
1.800 albertel 935: foreach my $server (keys(%servers)) {
936: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 937: }
1.344 www 938: }
939:
1.1023 raeburn 940: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 941: sub dump_dom {
1.1023 raeburn 942: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 943: if (!$udom) {
944: $udom=$env{'user.domain'};
945: }
946: my %returnhash;
1.1023 raeburn 947: if ($udom) {
948: my $uname = &get_domainconfiguser($udom);
949: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 950: }
951: return %returnhash;
952: }
953:
1.1023 raeburn 954: # ------------------------------------------ get items from domain db files
1.806 raeburn 955:
956: sub get_dom {
1.860 raeburn 957: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 958: my $items='';
959: foreach my $item (@$storearr) {
960: $items.=&escape($item).'&';
961: }
962: $items=~s/\&$//;
1.860 raeburn 963: if (!$udom) {
964: $udom=$env{'user.domain'};
965: if (defined(&domain($udom,'primary'))) {
966: $uhome=&domain($udom,'primary');
967: } else {
1.874 albertel 968: undef($uhome);
1.860 raeburn 969: }
970: } else {
971: if (!$uhome) {
972: if (defined(&domain($udom,'primary'))) {
973: $uhome=&domain($udom,'primary');
974: }
975: }
976: }
977: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 978: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 979: my %returnhash;
1.875 albertel 980: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 981: return %returnhash;
982: }
1.806 raeburn 983: my @pairs=split(/\&/,$rep);
984: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
985: return @pairs;
986: }
987: my $i=0;
988: foreach my $item (@$storearr) {
989: $returnhash{$item}=&thaw_unescape($pairs[$i]);
990: $i++;
991: }
992: return %returnhash;
993: } else {
1.880 banghart 994: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 995: }
996: }
997:
998: # -------------------------------------------- put items in domain db files
999:
1000: sub put_dom {
1.860 raeburn 1001: my ($namespace,$storehash,$udom,$uhome)=@_;
1002: if (!$udom) {
1003: $udom=$env{'user.domain'};
1004: if (defined(&domain($udom,'primary'))) {
1005: $uhome=&domain($udom,'primary');
1006: } else {
1.874 albertel 1007: undef($uhome);
1.860 raeburn 1008: }
1009: } else {
1010: if (!$uhome) {
1011: if (defined(&domain($udom,'primary'))) {
1012: $uhome=&domain($udom,'primary');
1013: }
1014: }
1015: }
1016: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1017: my $items='';
1018: foreach my $item (keys(%$storehash)) {
1019: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1020: }
1021: $items=~s/\&$//;
1022: return &reply("putdom:$udom:$namespace:$items",$uhome);
1023: } else {
1.860 raeburn 1024: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1025: }
1026: }
1027:
1.1023 raeburn 1028: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1029: sub newput_dom {
1.1023 raeburn 1030: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1031: my $result;
1032: if (!$udom) {
1033: $udom=$env{'user.domain'};
1034: }
1.1023 raeburn 1035: if ($udom) {
1036: my $uname = &get_domainconfiguser($udom);
1037: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1038: }
1039: return $result;
1040: }
1041:
1.1023 raeburn 1042: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1043: sub del_dom {
1.1023 raeburn 1044: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1045: if (ref($storearr) eq 'ARRAY') {
1046: if (!$udom) {
1047: $udom=$env{'user.domain'};
1048: }
1.1023 raeburn 1049: if ($udom) {
1050: my $uname = &get_domainconfiguser($udom);
1051: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1052: }
1053: }
1054: }
1055:
1.1023 raeburn 1056: # ----------------------------------construct domainconfig user for a domain
1057: sub get_domainconfiguser {
1058: my ($udom) = @_;
1059: return $udom.'-domainconfig';
1060: }
1061:
1.837 raeburn 1062: sub retrieve_inst_usertypes {
1063: my ($udom) = @_;
1064: my (%returnhash,@order);
1.989 raeburn 1065: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1066: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1067: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1068: %returnhash = %{$domdefs{'inststatustypes'}};
1069: @order = @{$domdefs{'inststatusorder'}};
1070: } else {
1071: if (defined(&domain($udom,'primary'))) {
1072: my $uhome=&domain($udom,'primary');
1073: my $rep=&reply("inst_usertypes:$udom",$uhome);
1074: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1075: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1076: return (\%returnhash,\@order);
1077: }
1078: my ($hashitems,$orderitems) = split(/:/,$rep);
1079: my @pairs=split(/\&/,$hashitems);
1080: foreach my $item (@pairs) {
1081: my ($key,$value)=split(/=/,$item,2);
1082: $key = &unescape($key);
1083: next if ($key =~ /^error: 2 /);
1084: $returnhash{$key}=&thaw_unescape($value);
1085: }
1086: my @esc_order = split(/\&/,$orderitems);
1087: foreach my $item (@esc_order) {
1088: push(@order,&unescape($item));
1089: }
1090: } else {
1091: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1092: }
1093: }
1094: return (\%returnhash,\@order);
1095: }
1096:
1.868 raeburn 1097: sub is_domainimage {
1098: my ($url) = @_;
1099: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1100: if (&domain($1) ne '') {
1101: return '1';
1102: }
1103: }
1104: return;
1105: }
1106:
1.899 raeburn 1107: sub inst_directory_query {
1108: my ($srch) = @_;
1109: my $udom = $srch->{'srchdomain'};
1110: my %results;
1111: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1112: my $outcome;
1.899 raeburn 1113: if ($homeserver ne '') {
1.904 albertel 1114: my $queryid=&reply("querysend:instdirsearch:".
1115: &escape($srch->{'srchby'}).':'.
1116: &escape($srch->{'srchterm'}).':'.
1117: &escape($srch->{'srchtype'}),$homeserver);
1118: my $host=&hostname($homeserver);
1119: if ($queryid !~/^\Q$host\E\_/) {
1120: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1121: return;
1122: }
1123: my $response = &get_query_reply($queryid);
1124: my $maxtries = 5;
1125: my $tries = 1;
1126: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1127: $response = &get_query_reply($queryid);
1128: $tries ++;
1129: }
1130:
1131: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1132: if ($response eq 'unavailable') {
1133: $outcome = $response;
1134: } else {
1135: $outcome = 'ok';
1136: my @matches = split(/\n/,$response);
1137: foreach my $match (@matches) {
1138: my ($key,$value) = split(/=/,$match);
1139: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1140: }
1.899 raeburn 1141: }
1142: }
1143: }
1.909 raeburn 1144: return ($outcome,%results);
1.899 raeburn 1145: }
1146:
1147: sub usersearch {
1148: my ($srch) = @_;
1149: my $dom = $srch->{'srchdomain'};
1150: my %results;
1151: my %libserv = &all_library();
1152: my $query = 'usersearch';
1153: foreach my $tryserver (keys(%libserv)) {
1154: if (&host_domain($tryserver) eq $dom) {
1155: my $host=&hostname($tryserver);
1156: my $queryid=
1.911 raeburn 1157: &reply("querysend:".&escape($query).':'.
1158: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1159: &escape($srch->{'srchtype'}).':'.
1160: &escape($srch->{'srchterm'}),$tryserver);
1161: if ($queryid !~/^\Q$host\E\_/) {
1162: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1163: next;
1.899 raeburn 1164: }
1165: my $reply = &get_query_reply($queryid);
1166: my $maxtries = 1;
1167: my $tries = 1;
1168: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1169: $reply = &get_query_reply($queryid);
1170: $tries ++;
1171: }
1172: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1173: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1174: } else {
1.911 raeburn 1175: my @matches;
1176: if ($reply =~ /\n/) {
1177: @matches = split(/\n/,$reply);
1178: } else {
1179: @matches = split(/\&/,$reply);
1180: }
1.899 raeburn 1181: foreach my $match (@matches) {
1182: my ($uname,$udom,%userhash);
1.911 raeburn 1183: foreach my $entry (split(/:/,$match)) {
1184: my ($key,$value) =
1185: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1186: $userhash{$key} = $value;
1187: if ($key eq 'username') {
1188: $uname = $value;
1189: } elsif ($key eq 'domain') {
1190: $udom = $value;
1.911 raeburn 1191: }
1.899 raeburn 1192: }
1193: $results{$uname.':'.$udom} = \%userhash;
1194: }
1195: }
1196: }
1197: }
1198: return %results;
1199: }
1200:
1.912 raeburn 1201: sub get_instuser {
1202: my ($udom,$uname,$id) = @_;
1203: my $homeserver = &domain($udom,'primary');
1204: my ($outcome,%results);
1205: if ($homeserver ne '') {
1206: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1207: &escape($id).':'.&escape($udom),$homeserver);
1208: my $host=&hostname($homeserver);
1209: if ($queryid !~/^\Q$host\E\_/) {
1210: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1211: return;
1212: }
1213: my $response = &get_query_reply($queryid);
1214: my $maxtries = 5;
1215: my $tries = 1;
1216: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1217: $response = &get_query_reply($queryid);
1218: $tries ++;
1219: }
1220: if (!&error($response) && $response ne 'refused') {
1221: if ($response eq 'unavailable') {
1222: $outcome = $response;
1223: } else {
1224: $outcome = 'ok';
1225: my @matches = split(/\n/,$response);
1226: foreach my $match (@matches) {
1227: my ($key,$value) = split(/=/,$match);
1228: $results{&unescape($key)} = &thaw_unescape($value);
1229: }
1230: }
1231: }
1232: }
1233: my %userinfo;
1234: if (ref($results{$uname}) eq 'HASH') {
1235: %userinfo = %{$results{$uname}};
1236: }
1237: return ($outcome,%userinfo);
1238: }
1239:
1240: sub inst_rulecheck {
1.923 raeburn 1241: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1242: my %returnhash;
1243: if ($udom ne '') {
1244: if (ref($rules) eq 'ARRAY') {
1245: @{$rules} = map {&escape($_);} (@{$rules});
1246: my $rulestr = join(':',@{$rules});
1247: my $homeserver=&domain($udom,'primary');
1248: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1249: my $response;
1250: if ($item eq 'username') {
1251: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1252: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1253: $homeserver));
1.923 raeburn 1254: } elsif ($item eq 'id') {
1255: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1256: ':'.&escape($id).':'.$rulestr,
1257: $homeserver));
1.945 raeburn 1258: } elsif ($item eq 'selfcreate') {
1259: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1260: &escape($udom).':'.&escape($uname).
1261: ':'.$rulestr,$homeserver));
1.923 raeburn 1262: }
1.912 raeburn 1263: if ($response ne 'refused') {
1264: my @pairs=split(/\&/,$response);
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: $returnhash{$key}=&thaw_unescape($value);
1270: }
1271: }
1272: }
1273: }
1274: }
1275: return %returnhash;
1276: }
1277:
1278: sub inst_userrules {
1.923 raeburn 1279: my ($udom,$check) = @_;
1.912 raeburn 1280: my (%ruleshash,@ruleorder);
1281: if ($udom ne '') {
1282: my $homeserver=&domain($udom,'primary');
1283: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1284: my $response;
1285: if ($check eq 'id') {
1286: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1287: $homeserver);
1.943 raeburn 1288: } elsif ($check eq 'email') {
1289: $response=&reply('instemailrules:'.&escape($udom),
1290: $homeserver);
1.923 raeburn 1291: } else {
1292: $response=&reply('instuserrules:'.&escape($udom),
1293: $homeserver);
1294: }
1.912 raeburn 1295: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1296: ($response ne 'unknown_cmd') &&
1.912 raeburn 1297: ($response ne 'no_such_host')) {
1298: my ($hashitems,$orderitems) = split(/:/,$response);
1299: my @pairs=split(/\&/,$hashitems);
1300: foreach my $item (@pairs) {
1301: my ($key,$value)=split(/=/,$item,2);
1302: $key = &unescape($key);
1303: next if ($key =~ /^error: 2 /);
1304: $ruleshash{$key}=&thaw_unescape($value);
1305: }
1306: my @esc_order = split(/\&/,$orderitems);
1307: foreach my $item (@esc_order) {
1308: push(@ruleorder,&unescape($item));
1309: }
1310: }
1311: }
1312: }
1313: return (\%ruleshash,\@ruleorder);
1314: }
1315:
1.976 raeburn 1316: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1317:
1318: sub get_domain_defaults {
1319: my ($domain) = @_;
1320: my $cachetime = 60*60*24;
1321: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1322: if (defined($cached)) {
1323: if (ref($result) eq 'HASH') {
1324: return %{$result};
1325: }
1326: }
1327: my %domdefaults;
1328: my %domconfig =
1.989 raeburn 1329: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1330: 'requestcourses','inststatus',
1331: 'coursedefaults'],$domain);
1.943 raeburn 1332: if (ref($domconfig{'defaults'}) eq 'HASH') {
1333: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1334: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1335: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1336: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1337: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1338: } else {
1339: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1340: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1341: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1342: }
1.976 raeburn 1343: if (ref($domconfig{'quotas'}) eq 'HASH') {
1344: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1345: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1346: } else {
1347: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1348: }
1349: my @usertools = ('aboutme','blog','portfolio');
1350: foreach my $item (@usertools) {
1351: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1352: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1353: }
1354: }
1355: }
1.985 raeburn 1356: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1357: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1358: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1359: }
1360: }
1.989 raeburn 1361: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1362: foreach my $item ('inststatustypes','inststatusorder') {
1363: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1364: }
1365: }
1.1047 raeburn 1366: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1367: foreach my $item ('canuse_pdfforms') {
1368: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1369: }
1370: }
1.943 raeburn 1371: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1372: $cachetime);
1373: return %domdefaults;
1374: }
1375:
1.344 www 1376: # --------------------------------------------------- Assign a key to a student
1377:
1378: sub assign_access_key {
1.364 www 1379: #
1380: # a valid key looks like uname:udom#comments
1381: # comments are being appended
1382: #
1.498 www 1383: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1384: $kdom=
1.620 albertel 1385: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1386: $knum=
1.620 albertel 1387: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1388: $cdom=
1.620 albertel 1389: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1390: $cnum=
1.620 albertel 1391: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1392: $udom=$env{'user.name'} unless (defined($udom));
1393: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1394: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1395: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1396: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1397: # assigned to this person
1398: # - this should not happen,
1.345 www 1399: # unless something went wrong
1400: # the first time around
1401: # ready to assign
1.364 www 1402: $logentry=$1.'; '.$logentry;
1.496 www 1403: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1404: $kdom,$knum) eq 'ok') {
1.345 www 1405: # key now belongs to user
1.346 www 1406: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1407: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1408: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1409: return 'ok';
1410: } else {
1411: return
1412: 'error: Count not permanently assign key, will need to be re-entered later.';
1413: }
1414: } else {
1415: return 'error: Could not assign key, try again later.';
1416: }
1.364 www 1417: } elsif (!$existing{$ckey}) {
1.345 www 1418: # the key does not exist
1419: return 'error: The key does not exist';
1420: } else {
1421: # the key is somebody else's
1422: return 'error: The key is already in use';
1423: }
1.344 www 1424: }
1425:
1.364 www 1426: # ------------------------------------------ put an additional comment on a key
1427:
1428: sub comment_access_key {
1429: #
1430: # a valid key looks like uname:udom#comments
1431: # comments are being appended
1432: #
1433: my ($ckey,$cdom,$cnum,$logentry)=@_;
1434: $cdom=
1.620 albertel 1435: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1436: $cnum=
1.620 albertel 1437: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1438: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1439: if ($existing{$ckey}) {
1440: $existing{$ckey}.='; '.$logentry;
1441: # ready to assign
1.367 www 1442: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1443: $cdom,$cnum) eq 'ok') {
1444: return 'ok';
1445: } else {
1446: return 'error: Count not store comment.';
1447: }
1448: } else {
1449: # the key does not exist
1450: return 'error: The key does not exist';
1451: }
1452: }
1453:
1.344 www 1454: # ------------------------------------------------------ Generate a set of keys
1455:
1456: sub generate_access_keys {
1.364 www 1457: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1462: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1463: unless (($cdom) && ($cnum)) { return 0; }
1464: if ($number>10000) { return 0; }
1465: sleep(2); # make sure don't get same seed twice
1466: srand(time()^($$+($$<<15))); # from "Programming Perl"
1467: my $total=0;
1468: for (my $i=1;$i<=$number;$i++) {
1469: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1470: sprintf("%lx",int(100000*rand)).'-'.
1471: sprintf("%lx",int(100000*rand));
1472: $newkey=~s/1/g/g; # folks mix up 1 and l
1473: $newkey=~s/0/h/g; # and also 0 and O
1474: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1475: if ($existing{$newkey}) {
1476: $i--;
1477: } else {
1.364 www 1478: if (&put('accesskeys',
1479: { $newkey => '# generated '.localtime().
1.620 albertel 1480: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1481: '; '.$logentry },
1482: $cdom,$cnum) eq 'ok') {
1.344 www 1483: $total++;
1484: }
1485: }
1486: }
1.620 albertel 1487: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1488: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1489: return $total;
1490: }
1491:
1492: # ------------------------------------------------------- Validate an accesskey
1493:
1494: sub validate_access_key {
1495: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1496: $cdom=
1.620 albertel 1497: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1498: $cnum=
1.620 albertel 1499: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1500: $udom=$env{'user.domain'} unless (defined($udom));
1501: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1502: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1503: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1504: }
1505:
1506: # ------------------------------------- Find the section of student in a course
1.652 albertel 1507: sub devalidate_getsection_cache {
1508: my ($udom,$unam,$courseid)=@_;
1509: my $hashid="$udom:$unam:$courseid";
1510: &devalidate_cache_new('getsection',$hashid);
1511: }
1.298 matthew 1512:
1.815 albertel 1513: sub courseid_to_courseurl {
1514: my ($courseid) = @_;
1515: #already url style courseid
1516: return $courseid if ($courseid =~ m{^/});
1517:
1518: if (exists($env{'course.'.$courseid.'.num'})) {
1519: my $cnum = $env{'course.'.$courseid.'.num'};
1520: my $cdom = $env{'course.'.$courseid.'.domain'};
1521: return "/$cdom/$cnum";
1522: }
1523:
1524: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1525: if (exists($courseinfo{'num'})) {
1526: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1527: }
1528:
1529: return undef;
1530: }
1531:
1.298 matthew 1532: sub getsection {
1533: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1534: my $cachetime=1800;
1.551 albertel 1535:
1536: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1537: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1538: if (defined($cached)) { return $result; }
1539:
1.298 matthew 1540: my %Pending;
1541: my %Expired;
1542: #
1543: # Each role can either have not started yet (pending), be active,
1544: # or have expired.
1545: #
1546: # If there is an active role, we are done.
1547: #
1548: # If there is more than one role which has not started yet,
1549: # choose the one which will start sooner
1550: # If there is one role which has not started yet, return it.
1551: #
1552: # If there is more than one expired role, choose the one which ended last.
1553: # If there is a role which has expired, return it.
1554: #
1.815 albertel 1555: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1556: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1557: foreach my $key (keys(%roleshash)) {
1.479 albertel 1558: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1559: my $section=$1;
1560: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1561: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1562: my $now=time;
1.548 albertel 1563: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1564: $Expired{$end}=$section;
1565: next;
1566: }
1.548 albertel 1567: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1568: $Pending{$start}=$section;
1569: next;
1570: }
1.599 albertel 1571: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1572: }
1573: #
1574: # Presumedly there will be few matching roles from the above
1575: # loop and the sorting time will be negligible.
1576: if (scalar(keys(%Pending))) {
1577: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1578: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1579: }
1580: if (scalar(keys(%Expired))) {
1581: my @sorted = sort {$a <=> $b} keys(%Expired);
1582: my $time = pop(@sorted);
1.599 albertel 1583: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1584: }
1.599 albertel 1585: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1586: }
1.70 www 1587:
1.599 albertel 1588: sub save_cache {
1589: &purge_remembered();
1.722 albertel 1590: #&Apache::loncommon::validate_page();
1.620 albertel 1591: undef(%env);
1.780 albertel 1592: undef($env_loaded);
1.599 albertel 1593: }
1.452 albertel 1594:
1.599 albertel 1595: my $to_remember=-1;
1596: my %remembered;
1597: my %accessed;
1598: my $kicks=0;
1599: my $hits=0;
1.849 albertel 1600: sub make_key {
1601: my ($name,$id) = @_;
1.872 albertel 1602: if (length($id) > 65
1603: && length(&escape($id)) > 200) {
1604: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1605: }
1.849 albertel 1606: return &escape($name.':'.$id);
1607: }
1608:
1.599 albertel 1609: sub devalidate_cache_new {
1610: my ($name,$id,$debug) = @_;
1611: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1612: $id=&make_key($name,$id);
1.599 albertel 1613: $memcache->delete($id);
1614: delete($remembered{$id});
1615: delete($accessed{$id});
1616: }
1617:
1618: sub is_cached_new {
1619: my ($name,$id,$debug) = @_;
1.849 albertel 1620: $id=&make_key($name,$id);
1.599 albertel 1621: if (exists($remembered{$id})) {
1622: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1623: $accessed{$id}=[&gettimeofday()];
1624: $hits++;
1625: return ($remembered{$id},1);
1626: }
1627: my $value = $memcache->get($id);
1628: if (!(defined($value))) {
1629: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1630: return (undef,undef);
1.416 albertel 1631: }
1.599 albertel 1632: if ($value eq '__undef__') {
1633: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1634: $value=undef;
1635: }
1636: &make_room($id,$value,$debug);
1637: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1638: return ($value,1);
1639: }
1640:
1641: sub do_cache_new {
1642: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1643: $id=&make_key($name,$id);
1.599 albertel 1644: my $setvalue=$value;
1645: if (!defined($setvalue)) {
1646: $setvalue='__undef__';
1647: }
1.623 albertel 1648: if (!defined($time) ) {
1649: $time=600;
1650: }
1.599 albertel 1651: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1652: my $result = $memcache->set($id,$setvalue,$time);
1653: if (! $result) {
1.872 albertel 1654: &logthis("caching of id -> $id failed");
1.910 albertel 1655: $memcache->disconnect_all();
1.872 albertel 1656: }
1.600 albertel 1657: # need to make a copy of $value
1.919 albertel 1658: &make_room($id,$value,$debug);
1.599 albertel 1659: return $value;
1660: }
1661:
1662: sub make_room {
1663: my ($id,$value,$debug)=@_;
1.919 albertel 1664:
1665: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1666: : $value;
1.599 albertel 1667: if ($to_remember<0) { return; }
1668: $accessed{$id}=[&gettimeofday()];
1669: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1670: my $to_kick;
1671: my $max_time=0;
1672: foreach my $other (keys(%accessed)) {
1673: if (&tv_interval($accessed{$other}) > $max_time) {
1674: $to_kick=$other;
1675: $max_time=&tv_interval($accessed{$other});
1676: }
1677: }
1678: delete($remembered{$to_kick});
1679: delete($accessed{$to_kick});
1680: $kicks++;
1681: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1682: return;
1683: }
1684:
1.599 albertel 1685: sub purge_remembered {
1.604 albertel 1686: #&logthis("Tossing ".scalar(keys(%remembered)));
1687: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1688: undef(%remembered);
1689: undef(%accessed);
1.428 albertel 1690: }
1.70 www 1691: # ------------------------------------- Read an entry from a user's environment
1692:
1693: sub userenvironment {
1694: my ($udom,$unam,@what)=@_;
1.976 raeburn 1695: my $items;
1696: foreach my $item (@what) {
1697: $items.=&escape($item).'&';
1698: }
1699: $items=~s/\&$//;
1.70 www 1700: my %returnhash=();
1.1009 raeburn 1701: my $uhome = &homeserver($unam,$udom);
1702: unless ($uhome eq 'no_host') {
1703: my @answer=split(/\&/,
1704: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1705: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1706: return %returnhash;
1707: }
1.1009 raeburn 1708: my $i;
1709: for ($i=0;$i<=$#what;$i++) {
1710: $returnhash{$what[$i]}=&unescape($answer[$i]);
1711: }
1.70 www 1712: }
1713: return %returnhash;
1.1 albertel 1714: }
1715:
1.617 albertel 1716: # ---------------------------------------------------------- Get a studentphoto
1717: sub studentphoto {
1718: my ($udom,$unam,$ext) = @_;
1719: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1720: if (defined($env{'request.course.id'})) {
1.708 raeburn 1721: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1722: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1723: return(&retrievestudentphoto($udom,$unam,$ext));
1724: } else {
1725: my ($result,$perm_reqd)=
1.707 albertel 1726: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1727: if ($result eq 'ok') {
1728: if (!($perm_reqd eq 'yes')) {
1729: return(&retrievestudentphoto($udom,$unam,$ext));
1730: }
1731: }
1732: }
1733: }
1734: } else {
1735: my ($result,$perm_reqd) =
1.707 albertel 1736: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1737: if ($result eq 'ok') {
1738: if (!($perm_reqd eq 'yes')) {
1739: return(&retrievestudentphoto($udom,$unam,$ext));
1740: }
1741: }
1742: }
1743: return '/adm/lonKaputt/lonlogo_broken.gif';
1744: }
1745:
1746: sub retrievestudentphoto {
1747: my ($udom,$unam,$ext,$type) = @_;
1748: my $home=&Apache::lonnet::homeserver($unam,$udom);
1749: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1750: if ($ret eq 'ok') {
1751: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1752: if ($type eq 'thumbnail') {
1753: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1754: }
1755: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1756: return $tokenurl;
1757: } else {
1758: if ($type eq 'thumbnail') {
1759: return '/adm/lonKaputt/genericstudent_tn.gif';
1760: } else {
1761: return '/adm/lonKaputt/lonlogo_broken.gif';
1762: }
1.617 albertel 1763: }
1764: }
1765:
1.263 www 1766: # -------------------------------------------------------------------- New chat
1767:
1768: sub chatsend {
1.724 raeburn 1769: my ($newentry,$anon,$group)=@_;
1.620 albertel 1770: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1771: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1772: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1773: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1774: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1775: &escape($newentry)).':'.$group,$chome);
1.292 www 1776: }
1777:
1778: # ------------------------------------------ Find current version of a resource
1779:
1780: sub getversion {
1781: my $fname=&clutter(shift);
1782: unless ($fname=~/^\/res\//) { return -1; }
1783: return ¤tversion(&filelocation('',$fname));
1784: }
1785:
1786: sub currentversion {
1787: my $fname=shift;
1.599 albertel 1788: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1789: if (defined($cached)) { return $result; }
1.292 www 1790: my $author=$fname;
1791: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1792: my ($udom,$uname)=split(/\//,$author);
1793: my $home=homeserver($uname,$udom);
1794: if ($home eq 'no_host') {
1795: return -1;
1796: }
1797: my $answer=reply("currentversion:$fname",$home);
1798: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1799: return -1;
1800: }
1.599 albertel 1801: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1802: }
1803:
1.1 albertel 1804: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1805:
1.1 albertel 1806: sub subscribe {
1807: my $fname=shift;
1.761 raeburn 1808: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1809: $fname=~s/[\n\r]//g;
1.1 albertel 1810: my $author=$fname;
1811: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1812: my ($udom,$uname)=split(/\//,$author);
1813: my $home=homeserver($uname,$udom);
1.335 albertel 1814: if ($home eq 'no_host') {
1815: return 'not_found';
1.1 albertel 1816: }
1817: my $answer=reply("sub:$fname",$home);
1.64 www 1818: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1819: $answer.=' by '.$home;
1820: }
1.1 albertel 1821: return $answer;
1822: }
1823:
1.8 www 1824: # -------------------------------------------------------------- Replicate file
1825:
1826: sub repcopy {
1827: my $filename=shift;
1.23 www 1828: $filename=~s/\/+/\//g;
1.607 raeburn 1829: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1830: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1831: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1832: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1833: return &repcopy_userfile($filename);
1834: }
1.532 albertel 1835: $filename=~s/[\n\r]//g;
1.8 www 1836: my $transname="$filename.in.transfer";
1.828 www 1837: # FIXME: this should flock
1.607 raeburn 1838: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1839: my $remoteurl=subscribe($filename);
1.64 www 1840: if ($remoteurl =~ /^con_lost by/) {
1841: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1842: return 'unavailable';
1.8 www 1843: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1844: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1845: return 'not_found';
1.64 www 1846: } elsif ($remoteurl =~ /^rejected by/) {
1847: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1848: return 'forbidden';
1.20 www 1849: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1850: return 'ok';
1.8 www 1851: } else {
1.290 www 1852: my $author=$filename;
1853: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1854: my ($udom,$uname)=split(/\//,$author);
1855: my $home=homeserver($uname,$udom);
1856: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1857: my @parts=split(/\//,$filename);
1858: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1859: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1860: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1861: return 'bad_request';
1.8 www 1862: }
1863: my $count;
1864: for ($count=5;$count<$#parts;$count++) {
1865: $path.="/$parts[$count]";
1866: if ((-e $path)!=1) {
1867: mkdir($path,0777);
1868: }
1869: }
1870: my $ua=new LWP::UserAgent;
1871: my $request=new HTTP::Request('GET',"$remoteurl");
1872: my $response=$ua->request($request,$transname);
1873: if ($response->is_error()) {
1874: unlink($transname);
1875: my $message=$response->status_line;
1.672 albertel 1876: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1877: ." LWP get: $message: $filename</font>");
1.607 raeburn 1878: return 'unavailable';
1.8 www 1879: } else {
1.16 www 1880: if ($remoteurl!~/\.meta$/) {
1881: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1882: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1883: if ($mresponse->is_error()) {
1884: unlink($filename.'.meta');
1885: &logthis(
1.672 albertel 1886: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1887: }
1888: }
1.8 www 1889: rename($transname,$filename);
1.607 raeburn 1890: return 'ok';
1.8 www 1891: }
1.290 www 1892: }
1.8 www 1893: }
1.330 www 1894: }
1895:
1896: # ------------------------------------------------ Get server side include body
1897: sub ssi_body {
1.381 albertel 1898: my ($filelink,%form)=@_;
1.606 matthew 1899: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1900: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1901: }
1.953 www 1902: my $output='';
1903: my $response;
1.980 raeburn 1904: if ($filelink=~/^https?\:/) {
1.954 raeburn 1905: ($output,$response)=&externalssi($filelink);
1.953 www 1906: } else {
1.1004 droeschl 1907: $filelink .= $filelink=~/\?/ ? '&' : '?';
1908: $filelink .= 'inhibitmenu=yes';
1.953 www 1909: ($output,$response)=&ssi($filelink,%form);
1910: }
1.778 albertel 1911: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1912: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1913: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1914: if (wantarray) {
1915: return ($output, $response);
1916: } else {
1917: return $output;
1918: }
1.8 www 1919: }
1920:
1.15 www 1921: # --------------------------------------------------------- Server Side Include
1922:
1.782 albertel 1923: sub absolute_url {
1924: my ($host_name) = @_;
1925: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1926: if ($host_name eq '') {
1927: $host_name = $ENV{'SERVER_NAME'};
1928: }
1929: return $protocol.$host_name;
1930: }
1931:
1.942 foxr 1932: #
1933: # Server side include.
1934: # Parameters:
1935: # fn Possibly encrypted resource name/id.
1936: # form Hash that describes how the rendering should be done
1937: # and other things.
1.944 foxr 1938: # Returns:
1.950 raeburn 1939: # Scalar context: The content of the response.
1940: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1941: #
1.15 www 1942: sub ssi {
1943:
1.944 foxr 1944: my ($fn,%form)=@_;
1.15 www 1945: my $ua=new LWP::UserAgent;
1.23 www 1946: my $request;
1.711 albertel 1947:
1948: $form{'no_update_last_known'}=1;
1.895 albertel 1949: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1950: if (%form) {
1.782 albertel 1951: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1952: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1953: } else {
1.782 albertel 1954: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1955: }
1956:
1.15 www 1957: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1958: my $response=$ua->request($request);
1959:
1.944 foxr 1960: if (wantarray) {
1961: return ($response->content, $response);
1962: } else {
1963: return $response->content;
1.942 foxr 1964: }
1.324 www 1965: }
1966:
1967: sub externalssi {
1968: my ($url)=@_;
1969: my $ua=new LWP::UserAgent;
1970: my $request=new HTTP::Request('GET',$url);
1971: my $response=$ua->request($request);
1.954 raeburn 1972: if (wantarray) {
1973: return ($response->content, $response);
1974: } else {
1975: return $response->content;
1976: }
1.15 www 1977: }
1.254 www 1978:
1.492 albertel 1979: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1980:
1981: sub allowuploaded {
1982: my ($srcurl,$url)=@_;
1983: $url=&clutter(&declutter($url));
1984: my $dir=$url;
1985: $dir=~s/\/[^\/]+$//;
1986: my %httpref=();
1987: my $httpurl=&hreflocation('',$url);
1988: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1989: &Apache::lonnet::appenv(\%httpref);
1.254 www 1990: }
1.477 raeburn 1991:
1.478 albertel 1992: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1993: # input: action, courseID, current domain, intended
1.637 raeburn 1994: # path to file, source of file, instruction to parse file for objects,
1995: # ref to hash for embedded objects,
1996: # ref to hash for codebase of java objects.
1997: #
1.485 raeburn 1998: # output: url to file (if action was uploaddoc),
1999: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2000: #
1.478 albertel 2001: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2002: # course.
1.477 raeburn 2003: #
1.478 albertel 2004: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2005: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2006: # course's home server.
1.477 raeburn 2007: #
1.478 albertel 2008: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2009: # be copied from $source (current location) to
2010: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2011: # and will then be copied to
2012: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2013: # course's home server.
1.485 raeburn 2014: #
1.481 raeburn 2015: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2016: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2017: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2018: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2019: # in course's home server.
1.637 raeburn 2020: #
1.477 raeburn 2021:
2022: sub process_coursefile {
1.638 albertel 2023: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2024: my $fetchresult;
1.638 albertel 2025: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2026: if ($action eq 'propagate') {
1.638 albertel 2027: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2028: $home);
1.481 raeburn 2029: } else {
1.477 raeburn 2030: my $fpath = '';
2031: my $fname = $file;
1.478 albertel 2032: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2033: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2034: my $filepath = &build_filepath($fpath);
1.481 raeburn 2035: if ($action eq 'copy') {
2036: if ($source eq '') {
2037: $fetchresult = 'no source file';
2038: return $fetchresult;
2039: } else {
2040: my $destination = $filepath.'/'.$fname;
2041: rename($source,$destination);
2042: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2043: $home);
1.481 raeburn 2044: }
2045: } elsif ($action eq 'uploaddoc') {
2046: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2047: print $fh $env{'form.'.$source};
1.481 raeburn 2048: close($fh);
1.637 raeburn 2049: if ($parser eq 'parse') {
1.1024 raeburn 2050: my $mm = new File::MMagic;
2051: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2052: if ($mime_type eq 'text/html') {
2053: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2054: unless ($parse_result eq 'ok') {
2055: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2056: }
1.637 raeburn 2057: }
2058: }
1.477 raeburn 2059: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2060: $home);
1.481 raeburn 2061: if ($fetchresult eq 'ok') {
2062: return '/uploaded/'.$fpath.'/'.$fname;
2063: } else {
2064: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2065: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2066: return '/adm/notfound.html';
2067: }
1.477 raeburn 2068: }
2069: }
1.485 raeburn 2070: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2071: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2072: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2073: }
2074: return $fetchresult;
2075: }
2076:
1.637 raeburn 2077: sub build_filepath {
2078: my ($fpath) = @_;
2079: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2080: unless ($fpath eq '') {
2081: my @parts=split('/',$fpath);
2082: foreach my $part (@parts) {
2083: $filepath.= '/'.$part;
2084: if ((-e $filepath)!=1) {
2085: mkdir($filepath,0777);
2086: }
2087: }
2088: }
2089: return $filepath;
2090: }
2091:
2092: sub store_edited_file {
1.638 albertel 2093: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2094: my $file = $primary_url;
2095: $file =~ s#^/uploaded/$docudom/$docuname/##;
2096: my $fpath = '';
2097: my $fname = $file;
2098: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2099: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2100: my $filepath = &build_filepath($fpath);
2101: open(my $fh,'>'.$filepath.'/'.$fname);
2102: print $fh $content;
2103: close($fh);
1.638 albertel 2104: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2105: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2106: $home);
1.637 raeburn 2107: if ($$fetchresult eq 'ok') {
2108: return '/uploaded/'.$fpath.'/'.$fname;
2109: } else {
1.638 albertel 2110: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2111: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2112: return '/adm/notfound.html';
2113: }
2114: }
2115:
1.531 albertel 2116: sub clean_filename {
1.831 albertel 2117: my ($fname,$args)=@_;
1.315 www 2118: # Replace Windows backslashes by forward slashes
1.257 www 2119: $fname=~s/\\/\//g;
1.831 albertel 2120: if (!$args->{'keep_path'}) {
2121: # Get rid of everything but the actual filename
2122: $fname=~s/^.*\/([^\/]+)$/$1/;
2123: }
1.315 www 2124: # Replace spaces by underscores
2125: $fname=~s/\s+/\_/g;
2126: # Replace all other weird characters by nothing
1.831 albertel 2127: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2128: # Replace all .\d. sequences with _\d. so they no longer look like version
2129: # numbers
2130: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2131: return $fname;
2132: }
1.1051 raeburn 2133: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2134: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2135: # image with the same aspect ratio as the original, but with dimensions which do
2136: # not exceed $resizewidth and $resizeheight.
2137:
1.984 neumanie 2138: sub resizeImage {
1.1051 raeburn 2139: my ($img_path,$resizewidth,$resizeheight) = @_;
2140: my $ima = Image::Magick->new;
2141: my $resized;
2142: if (-e $img_path) {
2143: $ima->Read($img_path);
2144: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2145: my $width = $ima->Get('width');
2146: my $height = $ima->Get('height');
2147: if ($width > $resizewidth) {
2148: my $factor = $width/$resizewidth;
2149: my $newheight = $height/$factor;
2150: $ima->Scale(width=>$resizewidth,height=>$newheight);
2151: $resized = 1;
2152: }
2153: }
2154: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2155: my $width = $ima->Get('width');
2156: my $height = $ima->Get('height');
2157: if ($height > $resizeheight) {
2158: my $factor = $height/$resizeheight;
2159: my $newwidth = $width/$factor;
2160: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2161: $resized = 1;
2162: }
2163: }
2164: if ($resized) {
2165: $ima->Write($img_path);
2166: }
2167: }
2168: return;
1.977 amueller 2169: }
2170:
1.608 albertel 2171: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2172: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2173: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2174: # $coursedoc - if true up to the current course
2175: # if false
2176: # $subdir - directory in userfile to store the file into
1.858 raeburn 2177: # $parser - instruction to parse file for objects ($parser = parse)
2178: # $allfiles - reference to hash for embedded objects
2179: # $codebase - reference to hash for codebase of java objects
2180: # $desuname - username for permanent storage of uploaded file
2181: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2182: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2183: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2184: # $resizewidth - width (pixels) to which to resize uploaded image
2185: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2186: #
1.686 albertel 2187: # output: url of file in userspace, or error: <message>
2188: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2189:
1.531 albertel 2190: sub userfileupload {
1.860 raeburn 2191: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2192: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2193: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2194: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2195: $fname=&clean_filename($fname);
1.315 www 2196: # See if there is anything left
1.257 www 2197: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2198: chop($env{'form.'.$formname});
1.523 raeburn 2199: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2200: my $now = time;
2201: my $filepath = 'tmp/helprequests/'.$now;
2202: my @parts=split(/\//,$filepath);
2203: my $fullpath = $perlvar{'lonDaemons'};
2204: for (my $i=0;$i<@parts;$i++) {
2205: $fullpath .= '/'.$parts[$i];
2206: if ((-e $fullpath)!=1) {
2207: mkdir($fullpath,0777);
2208: }
2209: }
2210: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2211: print $fh $env{'form.'.$formname};
1.523 raeburn 2212: close($fh);
1.741 raeburn 2213: return $fullpath.'/'.$fname;
2214: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2215: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2216: '_'.$env{'user.domain'}.'/pending';
2217: my @parts=split(/\//,$filepath);
2218: my $fullpath = $perlvar{'lonDaemons'};
2219: for (my $i=0;$i<@parts;$i++) {
2220: $fullpath .= '/'.$parts[$i];
2221: if ((-e $fullpath)!=1) {
2222: mkdir($fullpath,0777);
2223: }
2224: }
2225: open(my $fh,'>'.$fullpath.'/'.$fname);
2226: print $fh $env{'form.'.$formname};
2227: close($fh);
2228: return $fullpath.'/'.$fname;
1.523 raeburn 2229: }
1.995 raeburn 2230: if ($subdir eq 'scantron') {
2231: $fname = 'scantron_orig_'.$fname;
2232: } else {
1.258 www 2233: # Create the directory if not present
1.995 raeburn 2234: $fname="$subdir/$fname";
2235: }
1.259 www 2236: if ($coursedoc) {
1.638 albertel 2237: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2238: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2239: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2240: return &finishuserfileupload($docuname,$docudom,
2241: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2242: $codebase,$thumbwidth,$thumbheight,
2243: $resizewidth,$resizeheight);
1.481 raeburn 2244: } else {
1.620 albertel 2245: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2246: return &process_coursefile('uploaddoc',$docuname,$docudom,
2247: $fname,$formname,$parser,
2248: $allfiles,$codebase);
1.481 raeburn 2249: }
1.719 banghart 2250: } elsif (defined($destuname)) {
2251: my $docuname=$destuname;
2252: my $docudom=$destudom;
1.860 raeburn 2253: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2254: $parser,$allfiles,$codebase,
1.1051 raeburn 2255: $thumbwidth,$thumbheight,
2256: $resizewidth,$resizeheight);
1.719 banghart 2257:
1.259 www 2258: } else {
1.638 albertel 2259: my $docuname=$env{'user.name'};
2260: my $docudom=$env{'user.domain'};
1.714 raeburn 2261: if (exists($env{'form.group'})) {
2262: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2263: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2264: }
1.860 raeburn 2265: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2266: $parser,$allfiles,$codebase,
1.1051 raeburn 2267: $thumbwidth,$thumbheight,
2268: $resizewidth,$resizeheight);
1.259 www 2269: }
1.271 www 2270: }
2271:
2272: sub finishuserfileupload {
1.860 raeburn 2273: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2274: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2275: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2276: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2277:
1.860 raeburn 2278: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2279: $file=$fname;
2280: if ($fname=~m|/|) {
2281: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2282: $path.=$fnamepath.'/';
2283: }
1.259 www 2284: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2285: my $count;
2286: for ($count=4;$count<=$#parts;$count++) {
2287: $filepath.="/$parts[$count]";
2288: if ((-e $filepath)!=1) {
2289: mkdir($filepath,0777);
2290: }
2291: }
1.984 neumanie 2292:
1.258 www 2293: # Save the file
2294: {
1.701 albertel 2295: if (!open(FH,'>'.$filepath.'/'.$file)) {
2296: &logthis('Failed to create '.$filepath.'/'.$file);
2297: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2298: return '/adm/notfound.html';
2299: }
2300: if (!print FH ($env{'form.'.$formname})) {
2301: &logthis('Failed to write to '.$filepath.'/'.$file);
2302: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2303: return '/adm/notfound.html';
2304: }
1.570 albertel 2305: close(FH);
1.1051 raeburn 2306: if ($resizewidth && $resizeheight) {
2307: my $mm = new File::MMagic;
2308: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2309: if ($mime_type =~ m{^image/}) {
2310: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2311: }
1.977 amueller 2312: }
1.258 www 2313: }
1.637 raeburn 2314: if ($parser eq 'parse') {
1.1024 raeburn 2315: my $mm = new File::MMagic;
2316: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2317: if ($mime_type eq 'text/html') {
2318: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2319: $allfiles,$codebase);
2320: unless ($parse_result eq 'ok') {
2321: &logthis('Failed to parse '.$filepath.$file.
2322: ' for embedded media: '.$parse_result);
2323: }
1.637 raeburn 2324: }
2325: }
1.860 raeburn 2326: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2327: my $input = $filepath.'/'.$file;
2328: my $output = $filepath.'/'.'tn-'.$file;
2329: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2330: system("convert -sample $thumbsize $input $output");
2331: if (-e $filepath.'/'.'tn-'.$file) {
2332: $fetchthumb = 1;
2333: }
2334: }
1.858 raeburn 2335:
1.259 www 2336: # Notify homeserver to grep it
2337: #
1.984 neumanie 2338: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2339: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2340: if ($fetchresult eq 'ok') {
1.860 raeburn 2341: if ($fetchthumb) {
2342: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2343: if ($thumbresult ne 'ok') {
2344: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2345: $docuhome.': '.$thumbresult);
2346: }
2347: }
1.259 www 2348: #
1.258 www 2349: # Return the URL to it
1.494 albertel 2350: return '/uploaded/'.$path.$file;
1.263 www 2351: } else {
1.494 albertel 2352: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2353: ': '.$fetchresult);
1.263 www 2354: return '/adm/notfound.html';
1.858 raeburn 2355: }
1.493 albertel 2356: }
2357:
1.637 raeburn 2358: sub extract_embedded_items {
1.961 raeburn 2359: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2360: my @state = ();
2361: my %javafiles = (
2362: codebase => '',
2363: code => '',
2364: archive => ''
2365: );
2366: my %mediafiles = (
2367: src => '',
2368: movie => '',
2369: );
1.648 raeburn 2370: my $p;
2371: if ($content) {
2372: $p = HTML::LCParser->new($content);
2373: } else {
1.961 raeburn 2374: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2375: }
1.641 albertel 2376: while (my $t=$p->get_token()) {
1.640 albertel 2377: if ($t->[0] eq 'S') {
2378: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2379: push(@state, $tagname);
1.648 raeburn 2380: if (lc($tagname) eq 'allow') {
2381: &add_filetype($allfiles,$attr->{'src'},'src');
2382: }
1.640 albertel 2383: if (lc($tagname) eq 'img') {
2384: &add_filetype($allfiles,$attr->{'src'},'src');
2385: }
1.886 albertel 2386: if (lc($tagname) eq 'a') {
2387: &add_filetype($allfiles,$attr->{'href'},'href');
2388: }
1.645 raeburn 2389: if (lc($tagname) eq 'script') {
2390: if ($attr->{'archive'} =~ /\.jar$/i) {
2391: &add_filetype($allfiles,$attr->{'archive'},'archive');
2392: } else {
2393: &add_filetype($allfiles,$attr->{'src'},'src');
2394: }
2395: }
2396: if (lc($tagname) eq 'link') {
2397: if (lc($attr->{'rel'}) eq 'stylesheet') {
2398: &add_filetype($allfiles,$attr->{'href'},'href');
2399: }
2400: }
1.640 albertel 2401: if (lc($tagname) eq 'object' ||
2402: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2403: foreach my $item (keys(%javafiles)) {
2404: $javafiles{$item} = '';
2405: }
2406: }
2407: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2408: my $name = lc($attr->{'name'});
2409: foreach my $item (keys(%javafiles)) {
2410: if ($name eq $item) {
2411: $javafiles{$item} = $attr->{'value'};
2412: last;
2413: }
2414: }
2415: foreach my $item (keys(%mediafiles)) {
2416: if ($name eq $item) {
2417: &add_filetype($allfiles, $attr->{'value'}, 'value');
2418: last;
2419: }
2420: }
2421: }
2422: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2423: foreach my $item (keys(%javafiles)) {
2424: if ($attr->{$item}) {
2425: $javafiles{$item} = $attr->{$item};
2426: last;
2427: }
2428: }
2429: foreach my $item (keys(%mediafiles)) {
2430: if ($attr->{$item}) {
2431: &add_filetype($allfiles,$attr->{$item},$item);
2432: last;
2433: }
2434: }
2435: }
2436: } elsif ($t->[0] eq 'E') {
2437: my ($tagname) = ($t->[1]);
2438: if ($javafiles{'codebase'} ne '') {
2439: $javafiles{'codebase'} .= '/';
2440: }
2441: if (lc($tagname) eq 'applet' ||
2442: lc($tagname) eq 'object' ||
2443: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2444: ) {
2445: foreach my $item (keys(%javafiles)) {
2446: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2447: my $file=$javafiles{'codebase'}.$javafiles{$item};
2448: &add_filetype($allfiles,$file,$item);
2449: }
2450: }
2451: }
2452: pop @state;
2453: }
2454: }
1.637 raeburn 2455: return 'ok';
2456: }
2457:
1.639 albertel 2458: sub add_filetype {
2459: my ($allfiles,$file,$type)=@_;
2460: if (exists($allfiles->{$file})) {
2461: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2462: push(@{$allfiles->{$file}}, &escape($type));
2463: }
2464: } else {
2465: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2466: }
2467: }
2468:
1.493 albertel 2469: sub removeuploadedurl {
1.984 neumanie 2470: my ($url)=@_;
2471: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2472: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2473: }
2474:
2475: sub removeuserfile {
2476: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2477: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2478: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2479: if ($result eq 'ok') {
1.798 raeburn 2480: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2481: my $metafile = $fname.'.meta';
2482: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2483: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2484: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2485: my $sqlresult =
1.823 albertel 2486: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2487: 'portfolio_metadata',$group,
2488: 'delete');
1.798 raeburn 2489: }
2490: }
2491: return $result;
1.257 www 2492: }
1.15 www 2493:
1.530 albertel 2494: sub mkdiruserfile {
2495: my ($docuname,$docudom,$dir)=@_;
2496: my $home=&homeserver($docuname,$docudom);
2497: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2498: }
2499:
1.531 albertel 2500: sub renameuserfile {
2501: my ($docuname,$docudom,$old,$new)=@_;
2502: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2503: my $result = &reply("renameuserfile:$docudom:$docuname:".
2504: &escape("$old").':'.&escape("$new"),$home);
2505: if ($result eq 'ok') {
2506: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2507: my $oldmeta = $old.'.meta';
2508: my $newmeta = $new.'.meta';
2509: my $metaresult =
2510: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2511: my $url = "/uploaded/$docudom/$docuname/$old";
2512: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2513: my $sqlresult =
1.823 albertel 2514: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2515: 'portfolio_metadata',$group,
2516: 'delete');
1.798 raeburn 2517: }
2518: }
2519: return $result;
1.531 albertel 2520: }
2521:
1.14 www 2522: # ------------------------------------------------------------------------- Log
2523:
2524: sub log {
2525: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2526: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2527: }
2528:
2529: # ------------------------------------------------------------------ Course Log
1.352 www 2530: #
2531: # This routine flushes several buffers of non-mission-critical nature
2532: #
1.157 www 2533:
2534: sub flushcourselogs {
1.352 www 2535: &logthis('Flushing log buffers');
2536: #
2537: # course logs
2538: # This is a log of all transactions in a course, which can be used
2539: # for data mining purposes
2540: #
2541: # It also collects the courseid database, which lists last transaction
2542: # times and course titles for all courseids
2543: #
2544: my %courseidbuffer=();
1.921 raeburn 2545: foreach my $crsid (keys(%courselogs)) {
1.352 www 2546: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2547: &escape($courselogs{$crsid}),
2548: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2549: delete $courselogs{$crsid};
2550: } else {
2551: &logthis('Failed to flush log buffer for '.$crsid);
2552: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2553: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2554: " exceeded maximum size, deleting.</font>");
2555: delete $courselogs{$crsid};
2556: }
1.352 www 2557: }
1.920 raeburn 2558: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2559: 'description' => $coursedescrbuf{$crsid},
2560: 'inst_code' => $courseinstcodebuf{$crsid},
2561: 'type' => $coursetypebuf{$crsid},
2562: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2563: };
1.191 harris41 2564: }
1.352 www 2565: #
2566: # Write course id database (reverse lookup) to homeserver of courses
2567: # Is used in pickcourse
2568: #
1.840 albertel 2569: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2570: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2571: $courseidbuffer{$crs_home},
2572: $crs_home,'timeonly');
1.352 www 2573: }
2574: #
2575: # File accesses
2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
2577: #
1.449 matthew 2578: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2579: if ($entry =~ /___count$/) {
2580: my ($dom,$name);
1.807 albertel 2581: ($dom,$name,undef)=
1.811 albertel 2582: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2583: if (! defined($dom) || $dom eq '' ||
2584: ! defined($name) || $name eq '') {
1.620 albertel 2585: my $cid = $env{'request.course.id'};
2586: $dom = $env{'request.'.$cid.'.domain'};
2587: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2588: }
1.450 matthew 2589: my $value = $accesshash{$entry};
2590: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2591: my %temphash=($url => $value);
1.449 matthew 2592: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2593: if ($result eq 'ok') {
2594: delete $accesshash{$entry};
2595: } elsif ($result eq 'unknown_cmd') {
2596: # Target server has old code running on it.
1.450 matthew 2597: my %temphash=($entry => $value);
1.449 matthew 2598: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2599: delete $accesshash{$entry};
2600: }
2601: }
2602: } else {
1.811 albertel 2603: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2604: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2605: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2606: delete $accesshash{$entry};
2607: }
1.185 www 2608: }
1.191 harris41 2609: }
1.352 www 2610: #
2611: # Roles
2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
2613: #
1.800 albertel 2614: foreach my $entry (keys(%userrolehash)) {
1.351 www 2615: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2616: split(/\:/,$entry);
2617: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2618: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2619: $rudom,$runame) eq 'ok') {
2620: delete $userrolehash{$entry};
2621: }
2622: }
1.662 raeburn 2623: #
2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2625: #
2626: my %domrolebuffer = ();
1.1000 raeburn 2627: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2629: if ($domrolebuffer{$rudom}) {
2630: $domrolebuffer{$rudom}.='&'.&escape($entry).
2631: '='.&escape($domainrolehash{$entry});
2632: } else {
2633: $domrolebuffer{$rudom}.=&escape($entry).
2634: '='.&escape($domainrolehash{$entry});
2635: }
2636: delete $domainrolehash{$entry};
2637: }
2638: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2639: my %servers = &get_servers($dom,'library');
2640: foreach my $tryserver (keys(%servers)) {
2641: unless (&reply('domroleput:'.$dom.':'.
2642: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2643: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2644: }
1.662 raeburn 2645: }
2646: }
1.186 www 2647: $dumpcount++;
1.157 www 2648: }
2649:
2650: sub courselog {
2651: my $what=shift;
1.158 www 2652: $what=time.':'.$what;
1.620 albertel 2653: unless ($env{'request.course.id'}) { return ''; }
2654: $coursedombuf{$env{'request.course.id'}}=
2655: $env{'course.'.$env{'request.course.id'}.'.domain'};
2656: $coursenumbuf{$env{'request.course.id'}}=
2657: $env{'course.'.$env{'request.course.id'}.'.num'};
2658: $coursehombuf{$env{'request.course.id'}}=
2659: $env{'course.'.$env{'request.course.id'}.'.home'};
2660: $coursedescrbuf{$env{'request.course.id'}}=
2661: $env{'course.'.$env{'request.course.id'}.'.description'};
2662: $courseinstcodebuf{$env{'request.course.id'}}=
2663: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2664: $courseownerbuf{$env{'request.course.id'}}=
2665: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2666: $coursetypebuf{$env{'request.course.id'}}=
2667: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2668: if (defined $courselogs{$env{'request.course.id'}}) {
2669: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2670: } else {
1.620 albertel 2671: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2672: }
1.620 albertel 2673: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2674: &flushcourselogs();
2675: }
1.158 www 2676: }
2677:
2678: sub courseacclog {
2679: my $fnsymb=shift;
1.620 albertel 2680: unless ($env{'request.course.id'}) { return ''; }
2681: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2682: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2683: $what.=':POST';
1.583 matthew 2684: # FIXME: Probably ought to escape things....
1.800 albertel 2685: foreach my $key (keys(%env)) {
2686: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2687: my $formitem = $1;
2688: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2689: $what.=':'.$formitem.'='.$env{$key};
2690: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2691: $what.=':'.$formitem.'='.$env{$key};
2692: }
1.158 www 2693: }
1.191 harris41 2694: }
1.583 matthew 2695: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2696: # FIXME: We should not be depending on a form parameter that someone
2697: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2698: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2699: $what.= ':POST';
2700: # FIXME: Probably ought to escape things....
2701: foreach my $element ('courseexp','crsfulltext','crsrelated',
2702: 'crsdiscuss') {
1.620 albertel 2703: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2704: }
2705: }
1.158 www 2706: }
2707: &courselog($what);
1.149 www 2708: }
2709:
1.185 www 2710: sub countacc {
2711: my $url=&declutter(shift);
1.458 matthew 2712: return if (! defined($url) || $url eq '');
1.620 albertel 2713: unless ($env{'request.course.id'}) { return ''; }
2714: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2715: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2716: $accesshash{$key}++;
1.185 www 2717: }
1.349 www 2718:
1.361 www 2719: sub linklog {
2720: my ($from,$to)=@_;
2721: $from=&declutter($from);
2722: $to=&declutter($to);
2723: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2724: $accesshash{$to.'___'.$from.'___goto'}=1;
2725: }
2726:
1.349 www 2727: sub userrolelog {
2728: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2729: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2730: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2731: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2732: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2733: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2734: $userrolehash
2735: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2736: =$tend.':'.$tstart;
1.662 raeburn 2737: }
1.898 albertel 2738: if (($env{'request.role'} =~ /dc\./) &&
2739: (($trole=~/^au/) || ($trole=~/^in/) ||
2740: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2741: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2742: ($trole=~/^co/))) {
1.898 albertel 2743: $userrolehash
2744: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2745: =$tend.':'.$tstart;
2746: }
1.662 raeburn 2747: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2748: ($trole=~/^li/) || ($trole=~/^li/) ||
2749: ($trole=~/^au/) || ($trole=~/^dg/) ||
2750: ($trole=~/^sc/)) {
2751: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2752: $domainrolehash
2753: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2754: = $tend.':'.$tstart;
2755: }
1.351 www 2756: }
2757:
1.957 raeburn 2758: sub courserolelog {
2759: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2760: if (($trole eq 'cc') || ($trole eq 'in') ||
2761: ($trole eq 'ep') || ($trole eq 'ad') ||
2762: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2763: ($trole=~/^cr/) || ($trole eq 'gr') ||
2764: ($trole eq 'co')) {
1.957 raeburn 2765: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2766: my $cdom = $1;
2767: my $cnum = $2;
2768: my $sec = $3;
2769: my $namespace = 'rolelog';
2770: my %storehash = (
2771: role => $trole,
2772: start => $tstart,
2773: end => $tend,
2774: selfenroll => $selfenroll,
2775: context => $context,
2776: );
2777: if ($trole eq 'gr') {
2778: $namespace = 'groupslog';
2779: $storehash{'group'} = $sec;
2780: } else {
2781: $storehash{'section'} = $sec;
2782: }
2783: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2784: if (($trole ne 'st') || ($sec ne '')) {
2785: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2786: }
1.957 raeburn 2787: }
2788: }
2789: return;
2790: }
2791:
1.351 www 2792: sub get_course_adv_roles {
1.948 raeburn 2793: my ($cid,$codes) = @_;
1.620 albertel 2794: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2795: my %coursehash=&coursedescription($cid);
1.988 raeburn 2796: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2797: my %nothide=();
1.800 albertel 2798: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2799: if ($user !~ /:/) {
2800: $nothide{join(':',split(/[\@]/,$user))}=1;
2801: } else {
2802: $nothide{$user}=1;
2803: }
1.470 www 2804: }
1.351 www 2805: my %returnhash=();
2806: my %dumphash=
2807: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2808: my $now=time;
1.997 raeburn 2809: my %privileged;
1.1000 raeburn 2810: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2811: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2812: if (($tstart) && ($tstart<0)) { next; }
2813: if (($tend) && ($tend<$now)) { next; }
2814: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2815: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2816: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2817: unless (ref($privileged{$domain}) eq 'HASH') {
2818: my %dompersonnel =
1.998 raeburn 2819: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2820: $privileged{$domain} = {};
2821: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2822: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2823: foreach my $user (keys(%{$dompersonnel{$server}})) {
2824: my ($trole,$uname,$udom) = split(/:/,$user);
2825: $privileged{$udom}{$uname} = 1;
2826: }
2827: }
2828: }
2829: }
2830: if ((exists($privileged{$domain}{$username})) &&
2831: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2832: if ($role eq 'cr') { next; }
1.948 raeburn 2833: if ($codes) {
2834: if ($section) { $role .= ':'.$section; }
2835: if ($returnhash{$role}) {
2836: $returnhash{$role}.=','.$username.':'.$domain;
2837: } else {
2838: $returnhash{$role}=$username.':'.$domain;
2839: }
1.351 www 2840: } else {
1.988 raeburn 2841: my $key=&plaintext($role,$crstype);
1.973 bisitz 2842: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2843: if ($returnhash{$key}) {
2844: $returnhash{$key}.=','.$username.':'.$domain;
2845: } else {
2846: $returnhash{$key}=$username.':'.$domain;
2847: }
1.351 www 2848: }
1.948 raeburn 2849: }
1.400 www 2850: return %returnhash;
2851: }
2852:
2853: sub get_my_roles {
1.937 raeburn 2854: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2855: unless (defined($uname)) { $uname=$env{'user.name'}; }
2856: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2857: my (%dumphash,%nothide);
1.858 raeburn 2858: if ($context eq 'userroles') {
2859: %dumphash = &dump('roles',$udom,$uname);
2860: } else {
2861: %dumphash=
1.400 www 2862: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2863: if ($hidepriv) {
2864: my %coursehash=&coursedescription($udom.'_'.$uname);
2865: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2866: if ($user !~ /:/) {
2867: $nothide{join(':',split(/[\@]/,$user))} = 1;
2868: } else {
2869: $nothide{$user} = 1;
2870: }
2871: }
2872: }
1.858 raeburn 2873: }
1.400 www 2874: my %returnhash=();
2875: my $now=time;
1.999 raeburn 2876: my %privileged;
1.800 albertel 2877: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2878: my ($role,$tend,$tstart);
2879: if ($context eq 'userroles') {
2880: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2881: } else {
2882: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2883: }
1.400 www 2884: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2885: my $status = 'active';
1.939 raeburn 2886: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2887: $status = 'previous';
2888: }
2889: if (($tstart) && ($now<$tstart)) {
2890: $status = 'future';
2891: }
2892: if (ref($types) eq 'ARRAY') {
2893: if (!grep(/^\Q$status\E$/,@{$types})) {
2894: next;
2895: }
2896: } else {
2897: if ($status ne 'active') {
2898: next;
2899: }
2900: }
1.867 raeburn 2901: my ($rolecode,$username,$domain,$section,$area);
2902: if ($context eq 'userroles') {
2903: ($area,$rolecode) = split(/_/,$entry);
2904: (undef,$domain,$username,$section) = split(/\//,$area);
2905: } else {
2906: ($role,$username,$domain,$section) = split(/\:/,$entry);
2907: }
1.832 raeburn 2908: if (ref($roledoms) eq 'ARRAY') {
2909: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2910: next;
2911: }
2912: }
2913: if (ref($roles) eq 'ARRAY') {
2914: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2915: if ($role =~ /^cr\//) {
2916: if (!grep(/^cr$/,@{$roles})) {
2917: next;
2918: }
2919: } else {
2920: next;
2921: }
1.832 raeburn 2922: }
1.867 raeburn 2923: }
1.937 raeburn 2924: if ($hidepriv) {
1.999 raeburn 2925: if ($context eq 'userroles') {
2926: if ((&privileged($username,$domain)) &&
2927: (!$nothide{$username.':'.$domain})) {
2928: next;
2929: }
2930: } else {
2931: unless (ref($privileged{$domain}) eq 'HASH') {
2932: my %dompersonnel =
2933: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2934: $privileged{$domain} = {};
2935: if (keys(%dompersonnel)) {
2936: foreach my $server (keys(%dompersonnel)) {
2937: if (ref($dompersonnel{$server}) eq 'HASH') {
2938: foreach my $user (keys(%{$dompersonnel{$server}})) {
2939: my ($trole,$uname,$udom) = split(/:/,$user);
2940: $privileged{$udom}{$uname} = $trole;
2941: }
2942: }
2943: }
2944: }
2945: }
2946: if (exists($privileged{$domain}{$username})) {
2947: if (!$nothide{$username.':'.$domain}) {
2948: next;
2949: }
2950: }
1.937 raeburn 2951: }
2952: }
1.933 raeburn 2953: if ($withsec) {
2954: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2955: $tstart.':'.$tend;
2956: } else {
2957: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2958: }
1.832 raeburn 2959: }
1.373 www 2960: return %returnhash;
1.399 www 2961: }
2962:
2963: # ----------------------------------------------------- Frontpage Announcements
2964: #
2965: #
2966:
2967: sub postannounce {
2968: my ($server,$text)=@_;
1.844 albertel 2969: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2970: unless ($text=~/\w/) { $text=''; }
2971: return &reply('setannounce:'.&escape($text),$server);
2972: }
2973:
2974: sub getannounce {
1.448 albertel 2975:
2976: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2977: my $announcement='';
1.800 albertel 2978: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2979: close($fh);
1.399 www 2980: if ($announcement=~/\w/) {
2981: return
2982: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2983: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2984: } else {
2985: return '';
2986: }
2987: } else {
2988: return '';
2989: }
1.351 www 2990: }
1.353 www 2991:
2992: # ---------------------------------------------------------- Course ID routines
2993: # Deal with domain's nohist_courseid.db files
2994: #
2995:
2996: sub courseidput {
1.921 raeburn 2997: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 2998: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 2999: my $outcome;
3000: if ($caller eq 'timeonly') {
3001: my $cids = '';
3002: foreach my $item (keys(%$storehash)) {
3003: $cids.=&escape($item).'&';
3004: }
3005: $cids=~s/\&$//;
3006: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3007: $coursehome);
3008: } else {
3009: my $items = '';
3010: foreach my $item (keys(%$storehash)) {
3011: $items.= &escape($item).'='.
3012: &freeze_escape($$storehash{$item}).'&';
3013: }
3014: $items=~s/\&$//;
3015: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3016: $coursehome);
1.918 raeburn 3017: }
3018: if ($outcome eq 'unknown_cmd') {
3019: my $what;
3020: foreach my $cid (keys(%$storehash)) {
3021: $what .= &escape($cid).'=';
1.921 raeburn 3022: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3023: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3024: }
3025: $what =~ s/\:$/&/;
3026: }
3027: $what =~ s/\&$//;
3028: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3029: } else {
3030: return $outcome;
3031: }
1.353 www 3032: }
3033:
3034: sub courseiddump {
1.921 raeburn 3035: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3036: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3037: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3038: $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
1.918 raeburn 3039: my $as_hash = 1;
3040: my %returnhash;
3041: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3042: my %libserv = &all_library();
3043: foreach my $tryserver (keys(%libserv)) {
3044: if ( ( $hostidflag == 1
3045: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3046: || (!defined($hostidflag)) ) {
3047:
1.918 raeburn 3048: if (($domfilter eq '') ||
3049: (&host_domain($tryserver) eq $domfilter)) {
3050: my $rep =
3051: &reply('courseiddump:'.&host_domain($tryserver).':'.
3052: $sincefilter.':'.&escape($descfilter).':'.
3053: &escape($instcodefilter).':'.&escape($ownerfilter).
3054: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3055: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3056: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3057: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3058: &escape($cc_clone).':'.$cloneonly.':'.
3059: &escape($createdbefore).':'.&escape($createdafter).':'.
3060: &escape($creationcontext),$tryserver);
1.918 raeburn 3061: my @pairs=split(/\&/,$rep);
3062: foreach my $item (@pairs) {
3063: my ($key,$value)=split(/\=/,$item,2);
3064: $key = &unescape($key);
3065: next if ($key =~ /^error: 2 /);
3066: my $result = &thaw_unescape($value);
3067: if (ref($result) eq 'HASH') {
3068: $returnhash{$key}=$result;
3069: } else {
1.921 raeburn 3070: my @responses = split(/:/,$value);
3071: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3072: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3073: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3074: }
1.1008 raeburn 3075: }
1.353 www 3076: }
3077: }
3078: }
3079: }
3080: return %returnhash;
3081: }
3082:
1.1055 raeburn 3083: sub courselastaccess {
3084: my ($cdom,$cnum,$hostidref) = @_;
3085: my %returnhash;
3086: if ($cdom && $cnum) {
3087: my $chome = &homeserver($cnum,$cdom);
3088: if ($chome ne 'no_host') {
3089: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3090: &extract_lastaccess(\%returnhash,$rep);
3091: }
3092: } else {
3093: if (!$cdom) { $cdom=''; }
3094: my %libserv = &all_library();
3095: foreach my $tryserver (keys(%libserv)) {
3096: if (ref($hostidref) eq 'ARRAY') {
3097: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3098: }
3099: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3100: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3101: &extract_lastaccess(\%returnhash,$rep);
3102: }
3103: }
3104: }
3105: return %returnhash;
3106: }
3107:
3108: sub extract_lastaccess {
3109: my ($returnhash,$rep) = @_;
3110: if (ref($returnhash) eq 'HASH') {
3111: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3112: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3113: $rep eq '') {
3114: my @pairs=split(/\&/,$rep);
3115: foreach my $item (@pairs) {
3116: my ($key,$value)=split(/\=/,$item,2);
3117: $key = &unescape($key);
3118: next if ($key =~ /^error: 2 /);
3119: $returnhash->{$key} = &thaw_unescape($value);
3120: }
3121: }
3122: }
3123: return;
3124: }
3125:
1.658 raeburn 3126: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3127:
3128: sub dcmailput {
1.685 raeburn 3129: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3130: my $status = &Apache::lonnet::critical(
1.740 www 3131: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3132: &escape($message),$server);
1.662 raeburn 3133: return $status;
3134: }
3135:
1.658 raeburn 3136: sub dcmaildump {
3137: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3138: my %returnhash=();
1.846 albertel 3139:
3140: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3141: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3142: &escape($enddate).':';
3143: my @esc_senders=map { &escape($_)} @$senders;
3144: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3145: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3146: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3147: if (($key) && ($value)) {
3148: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3149: }
3150: }
3151: }
3152: return %returnhash;
3153: }
1.662 raeburn 3154: # ---------------------------------------------------------- Domain roles
3155:
3156: sub get_domain_roles {
3157: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3158: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3159: $startdate = '.';
3160: }
1.1018 raeburn 3161: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3162: $enddate = '.';
3163: }
1.922 raeburn 3164: my $rolelist;
3165: if (ref($roles) eq 'ARRAY') {
3166: $rolelist = join(':',@{$roles});
3167: }
1.662 raeburn 3168: my %personnel = ();
1.841 albertel 3169:
3170: my %servers = &get_servers($dom,'library');
3171: foreach my $tryserver (keys(%servers)) {
3172: %{$personnel{$tryserver}}=();
3173: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3174: &escape($startdate).':'.
3175: &escape($enddate).':'.
3176: &escape($rolelist), $tryserver))) {
3177: my ($key,$value) = split(/\=/,$line,2);
3178: if (($key) && ($value)) {
3179: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3180: }
3181: }
1.662 raeburn 3182: }
3183: return %personnel;
3184: }
1.658 raeburn 3185:
1.1057 www 3186: # ----------------------------------------------------------- Interval timing
1.149 www 3187:
1.504 albertel 3188: sub get_first_access {
3189: my ($type,$argsymb)=@_;
1.790 albertel 3190: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3191: if ($argsymb) { $symb=$argsymb; }
3192: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3193: if ($type eq 'course') {
3194: $res='course';
3195: } elsif ($type eq 'map') {
1.588 albertel 3196: $res=&symbread($map);
3197: } else {
3198: $res=$symb;
3199: }
3200: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3201: return $times{"$courseid\0$res"};
1.504 albertel 3202: }
3203:
3204: sub set_first_access {
3205: my ($type)=@_;
1.790 albertel 3206: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3207: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3208: if ($type eq 'course') {
3209: $res='course';
3210: } elsif ($type eq 'map') {
1.588 albertel 3211: $res=&symbread($map);
3212: } else {
3213: $res=$symb;
3214: }
3215: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3216: if (!$firstaccess) {
1.588 albertel 3217: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3218: }
3219: return 'already_set';
1.504 albertel 3220: }
3221:
1.110 www 3222: # --------------------------------------------- Set Expire Date for Spreadsheet
3223:
3224: sub expirespread {
3225: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3226: my $cid=$env{'request.course.id'};
1.110 www 3227: if ($cid) {
3228: my $now=time;
3229: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3230: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3231: $env{'course.'.$cid.'.num'}.
1.110 www 3232: ':nohist_expirationdates:'.
3233: &escape($key).'='.$now,
1.620 albertel 3234: $env{'course.'.$cid.'.home'})
1.110 www 3235: }
3236: return 'ok';
1.14 www 3237: }
3238:
1.109 www 3239: # ----------------------------------------------------- Devalidate Spreadsheets
3240:
3241: sub devalidate {
1.325 www 3242: my ($symb,$uname,$udom)=@_;
1.620 albertel 3243: my $cid=$env{'request.course.id'};
1.109 www 3244: if ($cid) {
1.391 matthew 3245: # delete the stored spreadsheets for
3246: # - the student level sheet of this user in course's homespace
3247: # - the assessment level sheet for this resource
3248: # for this user in user's homespace
1.553 albertel 3249: # - current conditional state info
1.325 www 3250: my $key=$uname.':'.$udom.':';
1.109 www 3251: my $status=
1.299 matthew 3252: &del('nohist_calculatedsheets',
1.391 matthew 3253: [$key.'studentcalc:'],
1.620 albertel 3254: $env{'course.'.$cid.'.domain'},
3255: $env{'course.'.$cid.'.num'})
1.133 albertel 3256: .' '.
3257: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3258: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3259: unless ($status eq 'ok ok') {
3260: &logthis('Could not devalidate spreadsheet '.
1.325 www 3261: $uname.' at '.$udom.' for '.
1.109 www 3262: $symb.': '.$status);
1.133 albertel 3263: }
1.553 albertel 3264: &delenv('user.state.'.$cid);
1.109 www 3265: }
3266: }
3267:
1.265 albertel 3268: sub get_scalar {
3269: my ($string,$end) = @_;
3270: my $value;
3271: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3272: $value = $1;
3273: } elsif ($$string =~ s/^([^&]*?)&//) {
3274: $value = $1;
3275: }
3276: return &unescape($value);
3277: }
3278:
3279: sub array2str {
3280: my (@array) = @_;
3281: my $result=&arrayref2str(\@array);
3282: $result=~s/^__ARRAY_REF__//;
3283: $result=~s/__END_ARRAY_REF__$//;
3284: return $result;
3285: }
3286:
1.204 albertel 3287: sub arrayref2str {
3288: my ($arrayref) = @_;
1.265 albertel 3289: my $result='__ARRAY_REF__';
1.204 albertel 3290: foreach my $elem (@$arrayref) {
1.265 albertel 3291: if(ref($elem) eq 'ARRAY') {
3292: $result.=&arrayref2str($elem).'&';
3293: } elsif(ref($elem) eq 'HASH') {
3294: $result.=&hashref2str($elem).'&';
3295: } elsif(ref($elem)) {
3296: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3297: } else {
3298: $result.=&escape($elem).'&';
3299: }
3300: }
3301: $result=~s/\&$//;
1.265 albertel 3302: $result .= '__END_ARRAY_REF__';
1.204 albertel 3303: return $result;
3304: }
3305:
1.168 albertel 3306: sub hash2str {
1.204 albertel 3307: my (%hash) = @_;
3308: my $result=&hashref2str(\%hash);
1.265 albertel 3309: $result=~s/^__HASH_REF__//;
3310: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3311: return $result;
3312: }
3313:
3314: sub hashref2str {
3315: my ($hashref)=@_;
1.265 albertel 3316: my $result='__HASH_REF__';
1.800 albertel 3317: foreach my $key (sort(keys(%$hashref))) {
3318: if (ref($key) eq 'ARRAY') {
3319: $result.=&arrayref2str($key).'=';
3320: } elsif (ref($key) eq 'HASH') {
3321: $result.=&hashref2str($key).'=';
3322: } elsif (ref($key)) {
1.265 albertel 3323: $result.='=';
1.800 albertel 3324: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3325: } else {
1.800 albertel 3326: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3327: }
3328:
1.800 albertel 3329: if(ref($hashref->{$key}) eq 'ARRAY') {
3330: $result.=&arrayref2str($hashref->{$key}).'&';
3331: } elsif(ref($hashref->{$key}) eq 'HASH') {
3332: $result.=&hashref2str($hashref->{$key}).'&';
3333: } elsif(ref($hashref->{$key})) {
1.265 albertel 3334: $result.='&';
1.800 albertel 3335: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3336: } else {
1.800 albertel 3337: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3338: }
3339: }
1.168 albertel 3340: $result=~s/\&$//;
1.265 albertel 3341: $result .= '__END_HASH_REF__';
1.168 albertel 3342: return $result;
3343: }
3344:
3345: sub str2hash {
1.265 albertel 3346: my ($string)=@_;
3347: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3348: return %$hash;
3349: }
3350:
3351: sub str2hashref {
1.168 albertel 3352: my ($string) = @_;
1.265 albertel 3353:
3354: my %hash;
3355:
3356: if($string !~ /^__HASH_REF__/) {
3357: if (! ($string eq '' || !defined($string))) {
3358: $hash{'error'}='Not hash reference';
3359: }
3360: return (\%hash, $string);
3361: }
3362:
3363: $string =~ s/^__HASH_REF__//;
3364:
3365: while($string !~ /^__END_HASH_REF__/) {
3366: #key
3367: my $key='';
3368: if($string =~ /^__HASH_REF__/) {
3369: ($key, $string)=&str2hashref($string);
3370: if(defined($key->{'error'})) {
3371: $hash{'error'}='Bad data';
3372: return (\%hash, $string);
3373: }
3374: } elsif($string =~ /^__ARRAY_REF__/) {
3375: ($key, $string)=&str2arrayref($string);
3376: if($key->[0] eq 'Array reference error') {
3377: $hash{'error'}='Bad data';
3378: return (\%hash, $string);
3379: }
3380: } else {
3381: $string =~ s/^(.*?)=//;
1.267 albertel 3382: $key=&unescape($1);
1.265 albertel 3383: }
3384: $string =~ s/^=//;
3385:
3386: #value
3387: my $value='';
3388: if($string =~ /^__HASH_REF__/) {
3389: ($value, $string)=&str2hashref($string);
3390: if(defined($value->{'error'})) {
3391: $hash{'error'}='Bad data';
3392: return (\%hash, $string);
3393: }
3394: } elsif($string =~ /^__ARRAY_REF__/) {
3395: ($value, $string)=&str2arrayref($string);
3396: if($value->[0] eq 'Array reference error') {
3397: $hash{'error'}='Bad data';
3398: return (\%hash, $string);
3399: }
3400: } else {
3401: $value=&get_scalar(\$string,'__END_HASH_REF__');
3402: }
3403: $string =~ s/^&//;
3404:
3405: $hash{$key}=$value;
1.204 albertel 3406: }
1.265 albertel 3407:
3408: $string =~ s/^__END_HASH_REF__//;
3409:
3410: return (\%hash, $string);
1.204 albertel 3411: }
3412:
3413: sub str2array {
1.265 albertel 3414: my ($string)=@_;
3415: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3416: return @$array;
3417: }
3418:
3419: sub str2arrayref {
1.204 albertel 3420: my ($string) = @_;
1.265 albertel 3421: my @array;
3422:
3423: if($string !~ /^__ARRAY_REF__/) {
3424: if (! ($string eq '' || !defined($string))) {
3425: $array[0]='Array reference error';
3426: }
3427: return (\@array, $string);
3428: }
3429:
3430: $string =~ s/^__ARRAY_REF__//;
3431:
3432: while($string !~ /^__END_ARRAY_REF__/) {
3433: my $value='';
3434: if($string =~ /^__HASH_REF__/) {
3435: ($value, $string)=&str2hashref($string);
3436: if(defined($value->{'error'})) {
3437: $array[0] ='Array reference error';
3438: return (\@array, $string);
3439: }
3440: } elsif($string =~ /^__ARRAY_REF__/) {
3441: ($value, $string)=&str2arrayref($string);
3442: if($value->[0] eq 'Array reference error') {
3443: $array[0] ='Array reference error';
3444: return (\@array, $string);
3445: }
3446: } else {
3447: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3448: }
3449: $string =~ s/^&//;
3450:
3451: push(@array, $value);
1.191 harris41 3452: }
1.265 albertel 3453:
3454: $string =~ s/^__END_ARRAY_REF__//;
3455:
3456: return (\@array, $string);
1.168 albertel 3457: }
3458:
1.167 albertel 3459: # -------------------------------------------------------------------Temp Store
3460:
1.168 albertel 3461: sub tmpreset {
3462: my ($symb,$namespace,$domain,$stuname) = @_;
3463: if (!$symb) {
3464: $symb=&symbread();
1.620 albertel 3465: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3466: }
3467: $symb=escape($symb);
3468:
1.620 albertel 3469: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3470: $namespace=~s/\//\_/g;
3471: $namespace=~s/\W//g;
3472:
1.620 albertel 3473: if (!$domain) { $domain=$env{'user.domain'}; }
3474: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3475: if ($domain eq 'public' && $stuname eq 'public') {
3476: $stuname=$ENV{'REMOTE_ADDR'};
3477: }
1.168 albertel 3478: my $path=$perlvar{'lonDaemons'}.'/tmp';
3479: my %hash;
3480: if (tie(%hash,'GDBM_File',
3481: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3482: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3483: foreach my $key (keys(%hash)) {
1.180 albertel 3484: if ($key=~ /:$symb/) {
1.168 albertel 3485: delete($hash{$key});
3486: }
3487: }
3488: }
3489: }
3490:
1.167 albertel 3491: sub tmpstore {
1.168 albertel 3492: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3493:
3494: if (!$symb) {
3495: $symb=&symbread();
1.620 albertel 3496: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3497: }
3498: $symb=escape($symb);
3499:
3500: if (!$namespace) {
3501: # I don't think we would ever want to store this for a course.
3502: # it seems this will only be used if we don't have a course.
1.620 albertel 3503: #$namespace=$env{'request.course.id'};
1.168 albertel 3504: #if (!$namespace) {
1.620 albertel 3505: $namespace=$env{'request.state'};
1.168 albertel 3506: #}
3507: }
3508: $namespace=~s/\//\_/g;
3509: $namespace=~s/\W//g;
1.620 albertel 3510: if (!$domain) { $domain=$env{'user.domain'}; }
3511: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3512: if ($domain eq 'public' && $stuname eq 'public') {
3513: $stuname=$ENV{'REMOTE_ADDR'};
3514: }
1.168 albertel 3515: my $now=time;
3516: my %hash;
3517: my $path=$perlvar{'lonDaemons'}.'/tmp';
3518: if (tie(%hash,'GDBM_File',
3519: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3520: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3521: $hash{"version:$symb"}++;
3522: my $version=$hash{"version:$symb"};
3523: my $allkeys='';
3524: foreach my $key (keys(%$storehash)) {
3525: $allkeys.=$key.':';
1.591 albertel 3526: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3527: }
3528: $hash{"$version:$symb:timestamp"}=$now;
3529: $allkeys.='timestamp';
3530: $hash{"$version:keys:$symb"}=$allkeys;
3531: if (untie(%hash)) {
3532: return 'ok';
3533: } else {
3534: return "error:$!";
3535: }
3536: } else {
3537: return "error:$!";
3538: }
3539: }
1.167 albertel 3540:
1.168 albertel 3541: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3542:
1.168 albertel 3543: sub tmprestore {
3544: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3545:
1.168 albertel 3546: if (!$symb) {
3547: $symb=&symbread();
1.620 albertel 3548: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3549: }
3550: $symb=escape($symb);
3551:
1.620 albertel 3552: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3553:
1.620 albertel 3554: if (!$domain) { $domain=$env{'user.domain'}; }
3555: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3556: if ($domain eq 'public' && $stuname eq 'public') {
3557: $stuname=$ENV{'REMOTE_ADDR'};
3558: }
1.168 albertel 3559: my %returnhash;
3560: $namespace=~s/\//\_/g;
3561: $namespace=~s/\W//g;
3562: my %hash;
3563: my $path=$perlvar{'lonDaemons'}.'/tmp';
3564: if (tie(%hash,'GDBM_File',
3565: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3566: &GDBM_READER(),0640)) {
1.168 albertel 3567: my $version=$hash{"version:$symb"};
3568: $returnhash{'version'}=$version;
3569: my $scope;
3570: for ($scope=1;$scope<=$version;$scope++) {
3571: my $vkeys=$hash{"$scope:keys:$symb"};
3572: my @keys=split(/:/,$vkeys);
3573: my $key;
3574: $returnhash{"$scope:keys"}=$vkeys;
3575: foreach $key (@keys) {
1.591 albertel 3576: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3577: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3578: }
3579: }
1.168 albertel 3580: if (!(untie(%hash))) {
3581: return "error:$!";
3582: }
3583: } else {
3584: return "error:$!";
3585: }
3586: return %returnhash;
1.167 albertel 3587: }
3588:
1.9 www 3589: # ----------------------------------------------------------------------- Store
3590:
3591: sub store {
1.124 www 3592: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3593: my $home='';
3594:
1.168 albertel 3595: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3596:
1.213 www 3597: $symb=&symbclean($symb);
1.122 albertel 3598: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3599:
1.620 albertel 3600: if (!$domain) { $domain=$env{'user.domain'}; }
3601: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3602:
3603: &devalidate($symb,$stuname,$domain);
1.109 www 3604:
3605: $symb=escape($symb);
1.187 www 3606: if (!$namespace) {
1.620 albertel 3607: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3608: return '';
3609: }
3610: }
1.620 albertel 3611: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3612:
3613: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3614: $$storehash{'host'}=$perlvar{'lonHostID'};
3615:
1.12 www 3616: my $namevalue='';
1.800 albertel 3617: foreach my $key (keys(%$storehash)) {
3618: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3619: }
1.12 www 3620: $namevalue=~s/\&$//;
1.187 www 3621: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3622: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3623: }
3624:
1.47 www 3625: # -------------------------------------------------------------- Critical Store
3626:
3627: sub cstore {
1.124 www 3628: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3629: my $home='';
3630:
1.168 albertel 3631: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3632:
1.213 www 3633: $symb=&symbclean($symb);
1.122 albertel 3634: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3635:
1.620 albertel 3636: if (!$domain) { $domain=$env{'user.domain'}; }
3637: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3638:
3639: &devalidate($symb,$stuname,$domain);
1.109 www 3640:
3641: $symb=escape($symb);
1.187 www 3642: if (!$namespace) {
1.620 albertel 3643: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3644: return '';
3645: }
3646: }
1.620 albertel 3647: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3648:
3649: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3650: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3651:
1.47 www 3652: my $namevalue='';
1.800 albertel 3653: foreach my $key (keys(%$storehash)) {
3654: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3655: }
1.47 www 3656: $namevalue=~s/\&$//;
1.187 www 3657: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3658: return critical
3659: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3660: }
3661:
1.9 www 3662: # --------------------------------------------------------------------- Restore
3663:
3664: sub restore {
1.124 www 3665: my ($symb,$namespace,$domain,$stuname) = @_;
3666: my $home='';
3667:
1.168 albertel 3668: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3669:
1.122 albertel 3670: if (!$symb) {
3671: unless ($symb=escape(&symbread())) { return ''; }
3672: } else {
1.213 www 3673: $symb=&escape(&symbclean($symb));
1.122 albertel 3674: }
1.188 www 3675: if (!$namespace) {
1.620 albertel 3676: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3677: return '';
3678: }
3679: }
1.620 albertel 3680: if (!$domain) { $domain=$env{'user.domain'}; }
3681: if (!$stuname) { $stuname=$env{'user.name'}; }
3682: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3683: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3684:
1.12 www 3685: my %returnhash=();
1.800 albertel 3686: foreach my $line (split(/\&/,$answer)) {
3687: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3688: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3689: }
1.75 www 3690: my $version;
3691: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3692: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3693: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3694: }
1.75 www 3695: }
1.13 www 3696: return %returnhash;
1.34 www 3697: }
3698:
3699: # ---------------------------------------------------------- Course Description
3700:
3701: sub coursedescription {
1.731 albertel 3702: my ($courseid,$args)=@_;
1.34 www 3703: $courseid=~s/^\///;
1.49 www 3704: $courseid=~s/\_/\//g;
1.34 www 3705: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3706: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3707: my $normalid=$cdomain.'_'.$cnum;
3708: # need to always cache even if we get errors otherwise we keep
3709: # trying and trying and trying to get the course description.
3710: my %envhash=();
3711: my %returnhash=();
1.731 albertel 3712:
3713: my $expiretime=600;
3714: if ($env{'request.course.id'} eq $normalid) {
3715: $expiretime=120;
3716: }
3717:
3718: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3719: if (!$args->{'freshen_cache'}
3720: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3721: foreach my $key (keys(%env)) {
3722: next if ($key !~ /^\Q$prefix\E(.*)/);
3723: my ($setting) = $1;
3724: $returnhash{$setting} = $env{$key};
3725: }
3726: return %returnhash;
3727: }
3728:
3729: # get the data agin
3730: if (!$args->{'one_time'}) {
3731: $envhash{'course.'.$normalid.'.last_cache'}=time;
3732: }
1.811 albertel 3733:
1.34 www 3734: if ($chome ne 'no_host') {
1.302 albertel 3735: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3736: if (!exists($returnhash{'con_lost'})) {
3737: $returnhash{'home'}= $chome;
3738: $returnhash{'domain'} = $cdomain;
3739: $returnhash{'num'} = $cnum;
1.741 raeburn 3740: if (!defined($returnhash{'type'})) {
3741: $returnhash{'type'} = 'Course';
3742: }
1.130 albertel 3743: while (my ($name,$value) = each %returnhash) {
1.53 www 3744: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3745: }
1.270 www 3746: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3747: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3748: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3749: $envhash{'course.'.$normalid.'.home'}=$chome;
3750: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3751: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3752: }
3753: }
1.731 albertel 3754: if (!$args->{'one_time'}) {
1.949 raeburn 3755: &appenv(\%envhash);
1.731 albertel 3756: }
1.302 albertel 3757: return %returnhash;
1.461 www 3758: }
3759:
3760: # -------------------------------------------------See if a user is privileged
3761:
3762: sub privileged {
3763: my ($username,$domain)=@_;
3764: my $rolesdump=&reply("dump:$domain:$username:roles",
3765: &homeserver($username,$domain));
1.1033 raeburn 3766: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3767: ($rolesdump =~ /^error:/)) {
3768: return 0;
3769: }
1.461 www 3770: my $now=time;
3771: if ($rolesdump ne '') {
1.800 albertel 3772: foreach my $entry (split(/&/,$rolesdump)) {
3773: if ($entry!~/^rolesdef_/) {
3774: my ($area,$role)=split(/=/,$entry);
1.461 www 3775: $area=~s/\_\w\w$//;
3776: my ($trole,$tend,$tstart)=split(/_/,$role);
3777: if (($trole eq 'dc') || ($trole eq 'su')) {
3778: my $active=1;
3779: if ($tend) {
3780: if ($tend<$now) { $active=0; }
3781: }
3782: if ($tstart) {
3783: if ($tstart>$now) { $active=0; }
3784: }
3785: if ($active) { return 1; }
3786: }
3787: }
3788: }
3789: }
3790: return 0;
1.9 www 3791: }
1.1 albertel 3792:
1.103 harris41 3793: # -------------------------------------------------------- Get user privileges
1.11 www 3794:
3795: sub rolesinit {
3796: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3797: my $now=time;
3798: my %userroles = ('user.login.time' => $now);
1.11 www 3799: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3800: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3801: ($rolesdump =~ /^error:/)) {
3802: return \%userroles;
3803: }
1.11 www 3804: my %allroles=();
1.678 raeburn 3805: my %allgroups=();
3806: my $group_privs;
1.11 www 3807:
3808: if ($rolesdump ne '') {
1.800 albertel 3809: foreach my $entry (split(/&/,$rolesdump)) {
3810: if ($entry!~/^rolesdef_/) {
3811: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3812: $area=~s/\_\w\w$//;
1.678 raeburn 3813: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3814: if ($role=~/^cr/) {
1.807 albertel 3815: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3816: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3817: ($tend,$tstart)=split('_',$trest);
3818: } else {
3819: $trole=$role;
3820: }
1.678 raeburn 3821: } elsif ($role =~ m|^gr/|) {
3822: ($trole,$tend,$tstart) = split(/_/,$role);
3823: ($trole,$group_privs) = split(/\//,$trole);
3824: $group_privs = &unescape($group_privs);
1.587 albertel 3825: } else {
3826: ($trole,$tend,$tstart)=split(/_/,$role);
3827: }
1.743 albertel 3828: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3829: $username);
3830: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3831: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3832: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3833: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3834: my $spec=$trole.'.'.$area;
3835: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3836: if ($trole =~ /^cr\//) {
1.567 raeburn 3837: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3838: } elsif ($trole eq 'gr') {
3839: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3840: } else {
1.567 raeburn 3841: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3842: }
1.12 www 3843: }
1.662 raeburn 3844: }
1.191 harris41 3845: }
1.743 albertel 3846: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3847: $userroles{'user.adv'} = $adv;
3848: $userroles{'user.author'} = $author;
1.620 albertel 3849: $env{'user.adv'}=$adv;
1.11 www 3850: }
1.743 albertel 3851: return \%userroles;
1.11 www 3852: }
3853:
1.567 raeburn 3854: sub set_arearole {
3855: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3856: # log the associated role with the area
3857: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3858: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3859: }
3860:
3861: sub custom_roleprivs {
3862: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3863: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3864: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3865: if (&hostname($homsvr) ne '') {
1.567 raeburn 3866: my ($rdummy,$roledef)=
3867: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3868: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3869: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3870: if (defined($syspriv)) {
1.1043 raeburn 3871: if ($trest =~ /^$match_community$/) {
3872: $syspriv =~ s/bre\&S//;
3873: }
1.567 raeburn 3874: $$allroles{'cm./'}.=':'.$syspriv;
3875: $$allroles{$spec.'./'}.=':'.$syspriv;
3876: }
3877: if ($tdomain ne '') {
3878: if (defined($dompriv)) {
3879: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3880: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3881: }
3882: if (($trest ne '') && (defined($coursepriv))) {
3883: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3884: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3885: }
3886: }
3887: }
3888: }
3889: }
3890:
1.678 raeburn 3891: sub group_roleprivs {
3892: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3893: my $access = 1;
3894: my $now = time;
3895: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3896: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3897: if ($access) {
1.811 albertel 3898: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3899: $$allgroups{$course}{$group} .=':'.$group_privs;
3900: }
3901: }
1.567 raeburn 3902:
3903: sub standard_roleprivs {
3904: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3905: if (defined($pr{$trole.':s'})) {
3906: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3907: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3908: }
3909: if ($tdomain ne '') {
3910: if (defined($pr{$trole.':d'})) {
3911: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3912: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3913: }
3914: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3915: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3916: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3917: }
3918: }
3919: }
3920:
3921: sub set_userprivs {
1.678 raeburn 3922: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3923: my $author=0;
3924: my $adv=0;
1.678 raeburn 3925: my %grouproles = ();
3926: if (keys(%{$allgroups}) > 0) {
1.1000 raeburn 3927: foreach my $role (keys(%{$allroles})) {
1.681 raeburn 3928: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3929: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3930: $trole = $1;
3931: $area = $2;
1.681 raeburn 3932: $sec = $3;
3933: $extendedarea = $area.$sec;
3934: if (exists($$allgroups{$area})) {
3935: foreach my $group (keys(%{$$allgroups{$area}})) {
3936: my $spec = $trole.'.'.$extendedarea;
3937: $grouproles{$spec.'.'.$area.'/'.$group} =
3938: $$allgroups{$area}{$group};
1.678 raeburn 3939: }
3940: }
3941: }
3942: }
3943: }
1.800 albertel 3944: foreach my $group (keys(%grouproles)) {
3945: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3946: }
1.800 albertel 3947: foreach my $role (keys(%{$allroles})) {
3948: my %thesepriv;
1.941 raeburn 3949: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3950: foreach my $item (split(/:/,$$allroles{$role})) {
3951: if ($item ne '') {
3952: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3953: if ($restrictions eq '') {
3954: $thesepriv{$privilege}='F';
3955: } elsif ($thesepriv{$privilege} ne 'F') {
3956: $thesepriv{$privilege}.=$restrictions;
3957: }
3958: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3959: }
3960: }
3961: my $thesestr='';
1.800 albertel 3962: foreach my $priv (keys(%thesepriv)) {
3963: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3964: }
3965: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3966: }
3967: return ($author,$adv);
3968: }
3969:
1.994 raeburn 3970: sub role_status {
1.1002 raeburn 3971: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 3972: my @pwhere = ();
3973: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
3974: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
3975: unless (!defined($$role) || $$role eq '') {
3976: $$where=join('.',@pwhere);
3977: $$trolecode=$$role.'.'.$$where;
3978: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
3979: $$tstatus='is';
3980: if ($$tstart && $$tstart>$then) {
3981: $$tstatus='future';
1.1034 raeburn 3982: if ($$tstart<$now) {
3983: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 3984: if (($$where ne '') && ($$role ne '')) {
3985: my (%allroles,%allgroups,$group_privs);
3986: my %userroles = (
3987: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
3988: );
3989: my $spec=$$role.'.'.$$where;
3990: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
3991: if ($$role =~ /^cr\//) {
3992: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
3993: } elsif ($$role eq 'gr') {
3994: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
3995: $env{'user.name'});
3996: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
3997: (undef,my $group_privs) = split(/\//,$trole);
3998: $group_privs = &unescape($group_privs);
3999: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4000: } else {
4001: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4002: }
4003: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4004: &appenv(\%userroles,[$$role,'cm']);
4005: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4006: }
4007: }
1.1034 raeburn 4008: $$tstatus = 'is';
1.1002 raeburn 4009: }
1.994 raeburn 4010: }
4011: if ($$tend) {
4012: if ($$tend<$then) {
4013: $$tstatus='expired';
4014: } elsif ($$tend<$now) {
4015: $$tstatus='will_not';
4016: }
4017: }
4018: }
4019: }
4020: }
4021:
4022: sub check_adhoc_privs {
1.1002 raeburn 4023: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4024: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4025: if ($env{$cckey}) {
4026: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4027: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4028: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4029: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4030: }
4031: } else {
4032: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4033: }
4034: }
4035:
4036: sub set_adhoc_privileges {
4037: # role can be cc or ca
4038: my ($dcdom,$pickedcourse,$role) = @_;
4039: my $area = '/'.$dcdom.'/'.$pickedcourse;
4040: my $spec = $role.'.'.$area;
4041: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4042: $env{'user.name'});
4043: my %ccrole = ();
4044: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4045: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4046: &appenv(\%userroles,[$role,'cm']);
4047: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4048: &appenv( {'request.role' => $spec,
4049: 'request.role.domain' => $dcdom,
4050: 'request.course.sec' => ''
4051: }
4052: );
4053: my $tadv=0;
4054: if (&allowed('adv') eq 'F') { $tadv=1; }
4055: &appenv({'request.role.adv' => $tadv});
4056: }
4057:
1.12 www 4058: # --------------------------------------------------------------- get interface
4059:
4060: sub get {
1.131 albertel 4061: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4062: my $items='';
1.800 albertel 4063: foreach my $item (@$storearr) {
4064: $items.=&escape($item).'&';
1.191 harris41 4065: }
1.12 www 4066: $items=~s/\&$//;
1.620 albertel 4067: if (!$udomain) { $udomain=$env{'user.domain'}; }
4068: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4069: my $uhome=&homeserver($uname,$udomain);
4070:
1.133 albertel 4071: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4072: my @pairs=split(/\&/,$rep);
1.273 albertel 4073: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4074: return @pairs;
4075: }
1.15 www 4076: my %returnhash=();
1.42 www 4077: my $i=0;
1.800 albertel 4078: foreach my $item (@$storearr) {
4079: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4080: $i++;
1.191 harris41 4081: }
1.15 www 4082: return %returnhash;
1.27 www 4083: }
4084:
4085: # --------------------------------------------------------------- del interface
4086:
4087: sub del {
1.133 albertel 4088: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4089: my $items='';
1.800 albertel 4090: foreach my $item (@$storearr) {
4091: $items.=&escape($item).'&';
1.191 harris41 4092: }
1.984 neumanie 4093:
1.27 www 4094: $items=~s/\&$//;
1.620 albertel 4095: if (!$udomain) { $udomain=$env{'user.domain'}; }
4096: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4097: my $uhome=&homeserver($uname,$udomain);
4098: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4099: }
4100:
4101: # -------------------------------------------------------------- dump interface
4102:
4103: sub dump {
1.755 albertel 4104: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4105: if (!$udomain) { $udomain=$env{'user.domain'}; }
4106: if (!$uname) { $uname=$env{'user.name'}; }
4107: my $uhome=&homeserver($uname,$udomain);
4108: if ($regexp) {
4109: $regexp=&escape($regexp);
4110: } else {
4111: $regexp='.';
4112: }
4113: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4114: my @pairs=split(/\&/,$rep);
4115: my %returnhash=();
4116: foreach my $item (@pairs) {
4117: my ($key,$value)=split(/=/,$item,2);
4118: $key = &unescape($key);
4119: next if ($key =~ /^error: 2 /);
4120: $returnhash{$key}=&thaw_unescape($value);
4121: }
4122: return %returnhash;
1.407 www 4123: }
4124:
1.717 albertel 4125: # --------------------------------------------------------- dumpstore interface
4126:
4127: sub dumpstore {
4128: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4129: if (!$udomain) { $udomain=$env{'user.domain'}; }
4130: if (!$uname) { $uname=$env{'user.name'}; }
4131: my $uhome=&homeserver($uname,$udomain);
4132: if ($regexp) {
4133: $regexp=&escape($regexp);
4134: } else {
4135: $regexp='.';
4136: }
4137: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4138: my @pairs=split(/\&/,$rep);
4139: my %returnhash=();
4140: foreach my $item (@pairs) {
4141: my ($key,$value)=split(/=/,$item,2);
4142: next if ($key =~ /^error: 2 /);
4143: $returnhash{$key}=&thaw_unescape($value);
4144: }
4145: return %returnhash;
1.717 albertel 4146: }
4147:
1.407 www 4148: # -------------------------------------------------------------- keys interface
4149:
4150: sub getkeys {
4151: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4152: if (!$udomain) { $udomain=$env{'user.domain'}; }
4153: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4154: my $uhome=&homeserver($uname,$udomain);
4155: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4156: my @keyarray=();
1.800 albertel 4157: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4158: next if ($key =~ /^error: 2 /);
1.800 albertel 4159: push(@keyarray,&unescape($key));
1.407 www 4160: }
4161: return @keyarray;
1.318 matthew 4162: }
4163:
1.319 matthew 4164: # --------------------------------------------------------------- currentdump
4165: sub currentdump {
1.328 matthew 4166: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4167: $courseid = $env{'request.course.id'} if (! defined($courseid));
4168: $sdom = $env{'user.domain'} if (! defined($sdom));
4169: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4170: my $uhome = &homeserver($sname,$sdom);
4171: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4172: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4173: #
1.318 matthew 4174: my %returnhash=();
1.319 matthew 4175: #
4176: if ($rep eq "unknown_cmd") {
4177: # an old lond will not know currentdump
4178: # Do a dump and make it look like a currentdump
1.822 albertel 4179: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4180: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4181: my %hash = @tmp;
4182: @tmp=();
1.424 matthew 4183: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4184: } else {
4185: my @pairs=split(/\&/,$rep);
1.800 albertel 4186: foreach my $pair (@pairs) {
4187: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4188: my ($symb,$param) = split(/:/,$key);
4189: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4190: &thaw_unescape($value);
1.319 matthew 4191: }
1.191 harris41 4192: }
1.12 www 4193: return %returnhash;
1.424 matthew 4194: }
4195:
4196: sub convert_dump_to_currentdump{
4197: my %hash = %{shift()};
4198: my %returnhash;
4199: # Code ripped from lond, essentially. The only difference
4200: # here is the unescaping done by lonnet::dump(). Conceivably
4201: # we might run in to problems with parameter names =~ /^v\./
4202: while (my ($key,$value) = each(%hash)) {
4203: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4204: $symb = &unescape($symb);
4205: $param = &unescape($param);
1.424 matthew 4206: next if ($v eq 'version' || $symb eq 'keys');
4207: next if (exists($returnhash{$symb}) &&
4208: exists($returnhash{$symb}->{$param}) &&
4209: $returnhash{$symb}->{'v.'.$param} > $v);
4210: $returnhash{$symb}->{$param}=$value;
4211: $returnhash{$symb}->{'v.'.$param}=$v;
4212: }
4213: #
4214: # Remove all of the keys in the hashes which keep track of
4215: # the version of the parameter.
4216: while (my ($symb,$param_hash) = each(%returnhash)) {
4217: # use a foreach because we are going to delete from the hash.
4218: foreach my $key (keys(%$param_hash)) {
4219: delete($param_hash->{$key}) if ($key =~ /^v\./);
4220: }
4221: }
4222: return \%returnhash;
1.12 www 4223: }
4224:
1.627 albertel 4225: # ------------------------------------------------------ critical inc interface
4226:
4227: sub cinc {
4228: return &inc(@_,'critical');
4229: }
4230:
1.449 matthew 4231: # --------------------------------------------------------------- inc interface
4232:
4233: sub inc {
1.627 albertel 4234: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4235: if (!$udomain) { $udomain=$env{'user.domain'}; }
4236: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4237: my $uhome=&homeserver($uname,$udomain);
4238: my $items='';
4239: if (! ref($store)) {
4240: # got a single value, so use that instead
4241: $items = &escape($store).'=&';
4242: } elsif (ref($store) eq 'SCALAR') {
4243: $items = &escape($$store).'=&';
4244: } elsif (ref($store) eq 'ARRAY') {
4245: $items = join('=&',map {&escape($_);} @{$store});
4246: } elsif (ref($store) eq 'HASH') {
4247: while (my($key,$value) = each(%{$store})) {
4248: $items.= &escape($key).'='.&escape($value).'&';
4249: }
4250: }
4251: $items=~s/\&$//;
1.627 albertel 4252: if ($critical) {
4253: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4254: } else {
4255: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4256: }
1.449 matthew 4257: }
4258:
1.12 www 4259: # --------------------------------------------------------------- put interface
4260:
4261: sub put {
1.134 albertel 4262: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4263: if (!$udomain) { $udomain=$env{'user.domain'}; }
4264: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4265: my $uhome=&homeserver($uname,$udomain);
1.12 www 4266: my $items='';
1.800 albertel 4267: foreach my $item (keys(%$storehash)) {
4268: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4269: }
1.12 www 4270: $items=~s/\&$//;
1.134 albertel 4271: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4272: }
4273:
1.631 albertel 4274: # ------------------------------------------------------------ newput interface
4275:
4276: sub newput {
4277: my ($namespace,$storehash,$udomain,$uname)=@_;
4278: if (!$udomain) { $udomain=$env{'user.domain'}; }
4279: if (!$uname) { $uname=$env{'user.name'}; }
4280: my $uhome=&homeserver($uname,$udomain);
4281: my $items='';
4282: foreach my $key (keys(%$storehash)) {
4283: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4284: }
4285: $items=~s/\&$//;
4286: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4287: }
4288:
4289: # --------------------------------------------------------- putstore interface
4290:
1.524 raeburn 4291: sub putstore {
1.715 albertel 4292: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4293: if (!$udomain) { $udomain=$env{'user.domain'}; }
4294: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4295: my $uhome=&homeserver($uname,$udomain);
4296: my $items='';
1.715 albertel 4297: foreach my $key (keys(%$storehash)) {
4298: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4299: }
1.715 albertel 4300: $items=~s/\&$//;
1.716 albertel 4301: my $esc_symb=&escape($symb);
4302: my $esc_v=&escape($version);
1.715 albertel 4303: my $reply =
1.716 albertel 4304: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4305: $uhome);
4306: if ($reply eq 'unknown_cmd') {
1.716 albertel 4307: # gfall back to way things use to be done
1.715 albertel 4308: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4309: $uname);
1.524 raeburn 4310: }
1.715 albertel 4311: return $reply;
4312: }
4313:
4314: sub old_putstore {
1.716 albertel 4315: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4316: if (!$udomain) { $udomain=$env{'user.domain'}; }
4317: if (!$uname) { $uname=$env{'user.name'}; }
4318: my $uhome=&homeserver($uname,$udomain);
4319: my %newstorehash;
1.800 albertel 4320: foreach my $item (keys(%$storehash)) {
4321: my $key = $version.':'.&escape($symb).':'.$item;
4322: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4323: }
4324: my $items='';
4325: my %allitems = ();
1.800 albertel 4326: foreach my $item (keys(%newstorehash)) {
4327: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4328: my $key = $1.':keys:'.$2;
4329: $allitems{$key} .= $3.':';
4330: }
1.800 albertel 4331: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4332: }
1.800 albertel 4333: foreach my $item (keys(%allitems)) {
4334: $allitems{$item} =~ s/\:$//;
4335: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4336: }
4337: $items=~s/\&$//;
4338: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4339: }
4340:
1.47 www 4341: # ------------------------------------------------------ critical put interface
4342:
4343: sub cput {
1.134 albertel 4344: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4345: if (!$udomain) { $udomain=$env{'user.domain'}; }
4346: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4347: my $uhome=&homeserver($uname,$udomain);
1.47 www 4348: my $items='';
1.800 albertel 4349: foreach my $item (keys(%$storehash)) {
4350: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4351: }
1.47 www 4352: $items=~s/\&$//;
1.134 albertel 4353: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4354: }
4355:
4356: # -------------------------------------------------------------- eget interface
4357:
4358: sub eget {
1.133 albertel 4359: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4360: my $items='';
1.800 albertel 4361: foreach my $item (@$storearr) {
4362: $items.=&escape($item).'&';
1.191 harris41 4363: }
1.12 www 4364: $items=~s/\&$//;
1.620 albertel 4365: if (!$udomain) { $udomain=$env{'user.domain'}; }
4366: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4367: my $uhome=&homeserver($uname,$udomain);
4368: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4369: my @pairs=split(/\&/,$rep);
4370: my %returnhash=();
1.42 www 4371: my $i=0;
1.800 albertel 4372: foreach my $item (@$storearr) {
4373: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4374: $i++;
1.191 harris41 4375: }
1.12 www 4376: return %returnhash;
4377: }
4378:
1.667 albertel 4379: # ------------------------------------------------------------ tmpput interface
4380: sub tmpput {
1.802 raeburn 4381: my ($storehash,$server,$context)=@_;
1.667 albertel 4382: my $items='';
1.800 albertel 4383: foreach my $item (keys(%$storehash)) {
4384: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4385: }
4386: $items=~s/\&$//;
1.802 raeburn 4387: if (defined($context)) {
4388: $items .= ':'.&escape($context);
4389: }
1.667 albertel 4390: return &reply("tmpput:$items",$server);
4391: }
4392:
4393: # ------------------------------------------------------------ tmpget interface
4394: sub tmpget {
1.688 albertel 4395: my ($token,$server)=@_;
4396: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4397: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4398: my %returnhash;
4399: foreach my $item (split(/\&/,$rep)) {
4400: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4401: next if ($key =~ /^error: 2 /);
1.667 albertel 4402: $returnhash{&unescape($key)}=&thaw_unescape($value);
4403: }
4404: return %returnhash;
4405: }
4406:
1.688 albertel 4407: # ------------------------------------------------------------ tmpget interface
4408: sub tmpdel {
4409: my ($token,$server)=@_;
4410: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4411: return &reply("tmpdel:$token",$server);
4412: }
4413:
1.765 albertel 4414: # -------------------------------------------------- portfolio access checking
4415:
4416: sub portfolio_access {
1.766 albertel 4417: my ($requrl) = @_;
1.765 albertel 4418: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4419: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4420: if ($result) {
4421: my %setters;
4422: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4423: my ($startblock,$endblock) =
4424: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4425: if ($startblock && $endblock) {
4426: return 'B';
4427: }
4428: } else {
4429: my ($startblock,$endblock) =
4430: &Apache::loncommon::blockcheck(\%setters,'port');
4431: if ($startblock && $endblock) {
4432: return 'B';
4433: }
4434: }
4435: }
1.765 albertel 4436: if ($result eq 'ok') {
1.766 albertel 4437: return 'F';
1.765 albertel 4438: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4439: return 'A';
1.765 albertel 4440: }
1.766 albertel 4441: return '';
1.765 albertel 4442: }
4443:
4444: sub get_portfolio_access {
1.767 albertel 4445: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4446:
4447: if (!ref($access_hash)) {
4448: my $current_perms = &get_portfile_permissions($udom,$unum);
4449: my %access_controls = &get_access_controls($current_perms,$group,
4450: $file_name);
4451: $access_hash = $access_controls{$file_name};
4452: }
4453:
1.765 albertel 4454: my ($public,$guest,@domains,@users,@courses,@groups);
4455: my $now = time;
4456: if (ref($access_hash) eq 'HASH') {
4457: foreach my $key (keys(%{$access_hash})) {
4458: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4459: if ($start > $now) {
4460: next;
4461: }
4462: if ($end && $end<$now) {
4463: next;
4464: }
4465: if ($scope eq 'public') {
4466: $public = $key;
4467: last;
4468: } elsif ($scope eq 'guest') {
4469: $guest = $key;
4470: } elsif ($scope eq 'domains') {
4471: push(@domains,$key);
4472: } elsif ($scope eq 'users') {
4473: push(@users,$key);
4474: } elsif ($scope eq 'course') {
4475: push(@courses,$key);
4476: } elsif ($scope eq 'group') {
4477: push(@groups,$key);
4478: }
4479: }
4480: if ($public) {
4481: return 'ok';
4482: }
4483: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4484: if ($guest) {
4485: return $guest;
4486: }
4487: } else {
4488: if (@domains > 0) {
4489: foreach my $domkey (@domains) {
4490: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4491: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4492: return 'ok';
4493: }
4494: }
4495: }
4496: }
4497: if (@users > 0) {
4498: foreach my $userkey (@users) {
1.865 raeburn 4499: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4500: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4501: if (ref($item) eq 'HASH') {
4502: if (($item->{'uname'} eq $env{'user.name'}) &&
4503: ($item->{'udom'} eq $env{'user.domain'})) {
4504: return 'ok';
4505: }
4506: }
4507: }
4508: }
1.765 albertel 4509: }
4510: }
4511: my %roleshash;
4512: my @courses_and_groups = @courses;
4513: push(@courses_and_groups,@groups);
4514: if (@courses_and_groups > 0) {
4515: my (%allgroups,%allroles);
4516: my ($start,$end,$role,$sec,$group);
4517: foreach my $envkey (%env) {
1.1060 raeburn 4518: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4519: my $cid = $2.'_'.$3;
4520: if ($1 eq 'gr') {
4521: $group = $4;
4522: $allgroups{$cid}{$group} = $env{$envkey};
4523: } else {
4524: if ($4 eq '') {
4525: $sec = 'none';
4526: } else {
4527: $sec = $4;
4528: }
4529: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4530: }
1.811 albertel 4531: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4532: my $cid = $2.'_'.$3;
4533: if ($4 eq '') {
4534: $sec = 'none';
4535: } else {
4536: $sec = $4;
4537: }
4538: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4539: }
4540: }
4541: if (keys(%allroles) == 0) {
4542: return;
4543: }
4544: foreach my $key (@courses_and_groups) {
4545: my %content = %{$$access_hash{$key}};
4546: my $cnum = $content{'number'};
4547: my $cdom = $content{'domain'};
4548: my $cid = $cdom.'_'.$cnum;
4549: if (!exists($allroles{$cid})) {
4550: next;
4551: }
4552: foreach my $role_id (keys(%{$content{'roles'}})) {
4553: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4554: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4555: my @status = @{$content{'roles'}{$role_id}{'access'}};
4556: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4557: foreach my $role (keys(%{$allroles{$cid}})) {
4558: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4559: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4560: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4561: if (grep/^all$/,@sections) {
4562: return 'ok';
4563: } else {
4564: if (grep/^$sec$/,@sections) {
4565: return 'ok';
4566: }
4567: }
4568: }
4569: }
4570: if (keys(%{$allgroups{$cid}}) == 0) {
4571: if (grep/^none$/,@groups) {
4572: return 'ok';
4573: }
4574: } else {
4575: if (grep/^all$/,@groups) {
4576: return 'ok';
4577: }
4578: foreach my $group (keys(%{$allgroups{$cid}})) {
4579: if (grep/^$group$/,@groups) {
4580: return 'ok';
4581: }
4582: }
4583: }
4584: }
4585: }
4586: }
4587: }
4588: }
4589: if ($guest) {
4590: return $guest;
4591: }
4592: }
4593: }
4594: return;
4595: }
4596:
4597: sub course_group_datechecker {
4598: my ($dates,$now,$status) = @_;
4599: my ($start,$end) = split(/\./,$dates);
4600: if (!$start && !$end) {
4601: return 'ok';
4602: }
4603: if (grep/^active$/,@{$status}) {
4604: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4605: return 'ok';
4606: }
4607: }
4608: if (grep/^previous$/,@{$status}) {
4609: if ($end > $now ) {
4610: return 'ok';
4611: }
4612: }
4613: if (grep/^future$/,@{$status}) {
4614: if ($start > $now) {
4615: return 'ok';
4616: }
4617: }
4618: return;
4619: }
4620:
4621: sub parse_portfolio_url {
4622: my ($url) = @_;
4623:
4624: my ($type,$udom,$unum,$group,$file_name);
4625:
1.823 albertel 4626: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4627: $type = 1;
4628: $udom = $1;
4629: $unum = $2;
4630: $file_name = $3;
1.823 albertel 4631: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4632: $type = 2;
4633: $udom = $1;
4634: $unum = $2;
4635: $group = $3;
4636: $file_name = $3.'/'.$4;
4637: }
4638: if (wantarray) {
4639: return ($type,$udom,$unum,$file_name,$group);
4640: }
4641: return $type;
4642: }
4643:
4644: sub is_portfolio_url {
4645: my ($url) = @_;
4646: return scalar(&parse_portfolio_url($url));
4647: }
4648:
1.798 raeburn 4649: sub is_portfolio_file {
4650: my ($file) = @_;
1.820 raeburn 4651: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4652: return 1;
4653: }
4654: return;
4655: }
4656:
1.976 raeburn 4657: sub usertools_access {
1.985 raeburn 4658: my ($uname,$udom,$tool,$action,$context) = @_;
4659: my ($access,%tools);
4660: if ($context eq '') {
4661: $context = 'tools';
4662: }
4663: if ($context eq 'requestcourses') {
4664: %tools = (
4665: official => 1,
4666: unofficial => 1,
1.1006 raeburn 4667: community => 1,
1.985 raeburn 4668: );
4669: } else {
4670: %tools = (
4671: aboutme => 1,
4672: blog => 1,
4673: portfolio => 1,
4674: );
4675: }
1.976 raeburn 4676: return if (!defined($tools{$tool}));
4677:
4678: if ((!defined($udom)) || (!defined($uname))) {
4679: $udom = $env{'user.domain'};
4680: $uname = $env{'user.name'};
4681: }
4682:
1.978 raeburn 4683: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4684: if ($action ne 'reload') {
1.985 raeburn 4685: if ($context eq 'requestcourses') {
4686: return $env{'environment.canrequest.'.$tool};
4687: } else {
4688: return $env{'environment.availabletools.'.$tool};
4689: }
4690: }
1.976 raeburn 4691: }
4692:
4693: my ($toolstatus,$inststatus);
4694:
1.985 raeburn 4695: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4696: ($action ne 'reload')) {
4697: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4698: $inststatus = $env{'environment.inststatus'};
4699: } else {
1.1025 raeburn 4700: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4701: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4702: $inststatus = $userenv{'inststatus'};
4703: }
4704:
4705: if ($toolstatus ne '') {
4706: if ($toolstatus) {
4707: $access = 1;
4708: } else {
4709: $access = 0;
4710: }
4711: return $access;
4712: }
4713:
4714: my $is_adv = &is_advanced_user($udom,$uname);
4715: my %domdef = &get_domain_defaults($udom);
4716: if (ref($domdef{$tool}) eq 'HASH') {
4717: if ($is_adv) {
4718: if ($domdef{$tool}{'_LC_adv'} ne '') {
4719: if ($domdef{$tool}{'_LC_adv'}) {
4720: $access = 1;
4721: } else {
4722: $access = 0;
4723: }
4724: return $access;
4725: }
4726: }
4727: if ($inststatus ne '') {
4728: my ($hasaccess,$hasnoaccess);
4729: foreach my $affiliation (split(/:/,$inststatus)) {
4730: if ($domdef{$tool}{$affiliation} ne '') {
4731: if ($domdef{$tool}{$affiliation}) {
4732: $hasaccess = 1;
4733: } else {
4734: $hasnoaccess = 1;
4735: }
4736: }
4737: }
4738: if ($hasaccess || $hasnoaccess) {
4739: if ($hasaccess) {
4740: $access = 1;
4741: } elsif ($hasnoaccess) {
4742: $access = 0;
4743: }
4744: return $access;
4745: }
4746: } else {
4747: if ($domdef{$tool}{'default'} ne '') {
4748: if ($domdef{$tool}{'default'}) {
4749: $access = 1;
4750: } elsif ($domdef{$tool}{'default'} == 0) {
4751: $access = 0;
4752: }
4753: return $access;
4754: }
4755: }
4756: } else {
1.985 raeburn 4757: if ($context eq 'tools') {
4758: $access = 1;
4759: } else {
4760: $access = 0;
4761: }
1.976 raeburn 4762: return $access;
4763: }
4764: }
4765:
1.1050 raeburn 4766: sub is_course_owner {
4767: my ($cdom,$cnum,$udom,$uname) = @_;
4768: if (($udom eq '') || ($uname eq '')) {
4769: $udom = $env{'user.domain'};
4770: $uname = $env{'user.name'};
4771: }
4772: unless (($udom eq '') || ($uname eq '')) {
4773: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4774: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4775: return 1;
4776: } else {
4777: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4778: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4779: return 1;
4780: }
4781: }
4782: }
4783: }
4784: return;
4785: }
4786:
1.976 raeburn 4787: sub is_advanced_user {
4788: my ($udom,$uname) = @_;
4789: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4790: my %allroles;
4791: my $is_adv;
4792: foreach my $role (keys(%roleshash)) {
4793: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4794: my $area = '/'.$tdomain.'/'.$trest;
4795: if ($sec ne '') {
4796: $area .= '/'.$sec;
4797: }
4798: if (($area ne '') && ($trole ne '')) {
4799: my $spec=$trole.'.'.$area;
4800: if ($trole =~ /^cr\//) {
4801: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4802: } elsif ($trole ne 'gr') {
4803: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4804: }
4805: }
4806: }
4807: foreach my $role (keys(%allroles)) {
4808: last if ($is_adv);
4809: foreach my $item (split(/:/,$allroles{$role})) {
4810: if ($item ne '') {
4811: my ($privilege,$restrictions)=split(/&/,$item);
4812: if ($privilege eq 'adv') {
4813: $is_adv = 1;
4814: last;
4815: }
4816: }
4817: }
4818: }
4819: return $is_adv;
4820: }
1.798 raeburn 4821:
1.1035 raeburn 4822: sub check_can_request {
1.1036 raeburn 4823: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 4824: my $canreq = 0;
4825: my ($types,$typename) = &Apache::loncommon::course_types();
4826: my @options = ('approval','validate','autolimit');
4827: my $optregex = join('|',@options);
4828: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4829: foreach my $type (@{$types}) {
4830: if (&usertools_access($env{'user.name'},
4831: $env{'user.domain'},
4832: $type,undef,'requestcourses')) {
4833: $canreq ++;
1.1036 raeburn 4834: if (ref($request_domains) eq 'HASH') {
4835: push(@{$request_domains->{$type}},$env{'user.domain'});
4836: }
1.1035 raeburn 4837: if ($dom eq $env{'user.domain'}) {
4838: $can_request->{$type} = 1;
4839: }
4840: }
4841: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
4842: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
4843: if (@curr > 0) {
1.1036 raeburn 4844: foreach my $item (@curr) {
4845: if (ref($request_domains) eq 'HASH') {
4846: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
4847: if ($otherdom ne '') {
4848: if (ref($request_domains->{$type}) eq 'ARRAY') {
4849: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
4850: push(@{$request_domains->{$type}},$otherdom);
4851: }
4852: } else {
4853: push(@{$request_domains->{$type}},$otherdom);
4854: }
4855: }
4856: }
4857: }
4858: unless($dom eq $env{'user.domain'}) {
4859: $canreq ++;
1.1035 raeburn 4860: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
4861: $can_request->{$type} = 1;
4862: }
4863: }
4864: }
4865: }
4866: }
4867: }
4868: return $canreq;
4869: }
4870:
1.341 www 4871: # ---------------------------------------------- Custom access rule evaluation
4872:
4873: sub customaccess {
4874: my ($priv,$uri)=@_;
1.807 albertel 4875: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4876: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4877: $udom = &LONCAPA::clean_domain($udom);
4878: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4879: my $access=0;
1.800 albertel 4880: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4881: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4882: if ($type eq 'user') {
4883: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4884: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4885: if ($tdom) {
4886: if ($tdom ne $env{'user.domain'}) { next; }
4887: }
1.896 albertel 4888: if ($tuname) {
4889: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4890: }
4891: $access=($effect eq 'allow');
4892: last;
4893: }
4894: } else {
4895: if ($role) {
4896: if ($role ne $urole) { next; }
4897: }
4898: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4899: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4900: if ($tdom) {
4901: if ($tdom ne $udom) { next; }
4902: }
4903: if ($tcrs) {
4904: if ($tcrs ne $ucrs) { next; }
4905: }
4906: if ($tsec) {
4907: if ($tsec ne $usec) { next; }
4908: }
4909: $access=($effect eq 'allow');
4910: last;
4911: }
4912: if ($realm eq '' && $role eq '') {
4913: $access=($effect eq 'allow');
4914: }
1.402 bowersj2 4915: }
1.341 www 4916: }
4917: return $access;
4918: }
4919:
1.103 harris41 4920: # ------------------------------------------------- Check for a user privilege
1.12 www 4921:
4922: sub allowed {
1.810 raeburn 4923: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4924: my $ver_orguri=$uri;
1.439 www 4925: $uri=&deversion($uri);
1.152 www 4926: my $orguri=$uri;
1.52 www 4927: $uri=&declutter($uri);
1.809 raeburn 4928:
1.810 raeburn 4929: if ($priv eq 'evb') {
4930: # Evade communication block restrictions for specified role in a course
4931: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4932: return $1;
4933: } else {
4934: return;
4935: }
4936: }
4937:
1.620 albertel 4938: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4939: # Free bre access to adm and meta resources
1.775 albertel 4940: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4941: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4942: && ($priv eq 'bre')) {
1.14 www 4943: return 'F';
1.159 www 4944: }
4945:
1.545 banghart 4946: # Free bre access to user's own portfolio contents
1.714 raeburn 4947: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4948: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4949: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4950: my %setters;
4951: my ($startblock,$endblock) =
4952: &Apache::loncommon::blockcheck(\%setters,'port');
4953: if ($startblock && $endblock) {
4954: return 'B';
4955: } else {
4956: return 'F';
4957: }
1.545 banghart 4958: }
4959:
1.762 raeburn 4960: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4961: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4962: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4963: if (exists($env{'request.course.id'})) {
4964: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4965: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4966: if (($domain eq $cdom) && ($name eq $cnum)) {
4967: my $courseprivid=$env{'request.course.id'};
4968: $courseprivid=~s/\_/\//;
4969: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4970: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4971: return $1;
1.762 raeburn 4972: } else {
4973: if ($env{'request.course.sec'}) {
4974: $courseprivid.='/'.$env{'request.course.sec'};
4975: }
4976: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4977: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4978: return $2;
4979: }
1.714 raeburn 4980: }
4981: }
4982: }
4983: }
4984:
1.159 www 4985: # Free bre to public access
4986:
4987: if ($priv eq 'bre') {
1.238 www 4988: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4989: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4990: return 'F';
4991: }
1.238 www 4992: if ($copyright eq 'priv') {
4993: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4994: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4995: return '';
4996: }
4997: }
4998: if ($copyright eq 'domain') {
4999: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5000: unless (($env{'user.domain'} eq $1) ||
5001: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5002: return '';
5003: }
1.262 matthew 5004: }
1.620 albertel 5005: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5006: # Library role, so allow browsing of resources in this domain.
5007: return 'F';
1.238 www 5008: }
1.341 www 5009: if ($copyright eq 'custom') {
5010: unless (&customaccess($priv,$uri)) { return ''; }
5011: }
1.14 www 5012: }
1.264 matthew 5013: # Domain coordinator is trying to create a course
1.620 albertel 5014: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5015: # uri is the requested domain in this case.
5016: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5017: # a role of dc for the domain in question.
1.620 albertel 5018: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5019: }
1.29 www 5020:
1.52 www 5021: my $thisallowed='';
5022: my $statecond=0;
5023: my $courseprivid='';
5024:
1.1039 raeburn 5025: my $ownaccess;
1.1043 raeburn 5026: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5027: if (($priv eq 'bro') && ($env{'user.author'})) {
5028: if ($uri eq '') {
5029: $ownaccess = 1;
5030: } else {
5031: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5032: my $udom = $env{'user.domain'};
5033: my $uname = $env{'user.name'};
5034: if ($uri =~ m{^\Q$udom\E/?$}) {
5035: $ownaccess = 1;
1.1040 raeburn 5036: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5037: unless ($uri =~ m{\.\./}) {
5038: $ownaccess = 1;
5039: }
5040: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5041: my $now = time;
5042: if ($uri =~ m{^([^/]+)/?$}) {
5043: my $adom = $1;
5044: foreach my $key (keys(%env)) {
1.1042 raeburn 5045: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5046: my ($start,$end) = split('.',$env{$key});
5047: if (($now >= $start) && (!$end || $end < $now)) {
5048: $ownaccess = 1;
5049: last;
5050: }
5051: }
5052: }
5053: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5054: my $adom = $1;
5055: my $aname = $2;
1.1042 raeburn 5056: foreach my $role ('ca','aa') {
5057: if ($env{"user.role.$role./$adom/$aname"}) {
5058: my ($start,$end) =
5059: split('.',$env{"user.role.$role./$adom/$aname"});
5060: if (($now >= $start) && (!$end || $end < $now)) {
5061: $ownaccess = 1;
5062: last;
5063: }
1.1039 raeburn 5064: }
5065: }
5066: }
5067: }
5068: }
5069: }
5070: }
5071:
1.52 www 5072: # Course
5073:
1.620 albertel 5074: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5075: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5076: $thisallowed.=$1;
5077: }
1.52 www 5078: }
1.29 www 5079:
1.52 www 5080: # Domain
5081:
1.620 albertel 5082: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5083: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5084: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5085: $thisallowed.=$1;
5086: }
1.12 www 5087: }
1.52 www 5088:
5089: # Course: uri itself is a course
1.66 www 5090: my $courseuri=$uri;
5091: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5092: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5093:
1.620 albertel 5094: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5095: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5096: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5097: $thisallowed.=$1;
5098: }
1.12 www 5099: }
1.29 www 5100:
1.665 albertel 5101: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5102: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5103: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5104: $thisallowed='';
1.671 raeburn 5105: my ($match)=&is_on_map($uri);
5106: if ($match) {
5107: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5108: =~/\Q$priv\E\&([^\:]*)/) {
5109: $thisallowed.=$1;
5110: }
5111: } else {
1.705 albertel 5112: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5113: if ($refuri) {
5114: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5115: $thisallowed='F';
1.671 raeburn 5116: } else {
5117: $refuri=&declutter($refuri);
5118: my ($match) = &is_on_map($refuri);
5119: if ($match) {
5120: $thisallowed='F';
5121: }
1.669 raeburn 5122: }
1.671 raeburn 5123: }
5124: }
1.314 www 5125: }
1.492 albertel 5126:
1.766 albertel 5127: if ($priv eq 'bre'
5128: && $thisallowed ne 'F'
5129: && $thisallowed ne '2'
5130: && &is_portfolio_url($uri)) {
5131: $thisallowed = &portfolio_access($uri);
5132: }
5133:
1.52 www 5134: # Full access at system, domain or course-wide level? Exit.
1.29 www 5135: if ($thisallowed=~/F/) {
5136: return 'F';
5137: }
5138:
1.52 www 5139: # If this is generating or modifying users, exit with special codes
1.29 www 5140:
1.643 www 5141: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5142: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5143: my ($audom,$auname)=split('/',$uri);
1.643 www 5144: # no author name given, so this just checks on the general right to make a co-author in this domain
5145: unless ($auname) { return $thisallowed; }
5146: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5147: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5148: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5149: ($audom ne $env{'request.role.domain'}))) { return ''; }
5150: }
1.52 www 5151: return $thisallowed;
5152: }
5153: #
1.103 harris41 5154: # Gathered so far: system, domain and course wide privileges
1.52 www 5155: #
5156: # Course: See if uri or referer is an individual resource that is part of
5157: # the course
5158:
1.620 albertel 5159: if ($env{'request.course.id'}) {
1.232 www 5160:
1.620 albertel 5161: $courseprivid=$env{'request.course.id'};
5162: if ($env{'request.course.sec'}) {
5163: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5164: }
5165: $courseprivid=~s/\_/\//;
5166: my $checkreferer=1;
1.232 www 5167: my ($match,$cond)=&is_on_map($uri);
5168: if ($match) {
5169: $statecond=$cond;
1.620 albertel 5170: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5171: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5172: $thisallowed.=$1;
5173: $checkreferer=0;
5174: }
1.29 www 5175: }
1.83 www 5176:
1.148 www 5177: if ($checkreferer) {
1.620 albertel 5178: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5179: unless ($refuri) {
1.800 albertel 5180: foreach my $key (keys(%env)) {
5181: if ($key=~/^httpref\..*\*/) {
5182: my $pattern=$key;
1.156 www 5183: $pattern=~s/^httpref\.\/res\///;
1.148 www 5184: $pattern=~s/\*/\[\^\/\]\+/g;
5185: $pattern=~s/\//\\\//g;
1.152 www 5186: if ($orguri=~/$pattern/) {
1.800 albertel 5187: $refuri=$env{$key};
1.148 www 5188: }
5189: }
1.191 harris41 5190: }
1.148 www 5191: }
1.232 www 5192:
1.148 www 5193: if ($refuri) {
1.152 www 5194: $refuri=&declutter($refuri);
1.232 www 5195: my ($match,$cond)=&is_on_map($refuri);
5196: if ($match) {
5197: my $refstatecond=$cond;
1.620 albertel 5198: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5199: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5200: $thisallowed.=$1;
1.53 www 5201: $uri=$refuri;
5202: $statecond=$refstatecond;
1.52 www 5203: }
5204: }
1.148 www 5205: }
1.29 www 5206: }
1.52 www 5207: }
1.29 www 5208:
1.52 www 5209: #
1.103 harris41 5210: # Gathered now: all privileges that could apply, and condition number
1.52 www 5211: #
5212: #
5213: # Full or no access?
5214: #
1.29 www 5215:
1.52 www 5216: if ($thisallowed=~/F/) {
5217: return 'F';
5218: }
1.29 www 5219:
1.52 www 5220: unless ($thisallowed) {
5221: return '';
5222: }
1.29 www 5223:
1.52 www 5224: # Restrictions exist, deal with them
5225: #
5226: # C:according to course preferences
5227: # R:according to resource settings
5228: # L:unless locked
5229: # X:according to user session state
5230: #
5231:
5232: # Possibly locked functionality, check all courses
1.54 www 5233: # Locks might take effect only after 10 minutes cache expiration for other
5234: # courses, and 2 minutes for current course
1.52 www 5235:
5236: my $envkey;
5237: if ($thisallowed=~/L/) {
1.1000 raeburn 5238: foreach $envkey (keys(%env)) {
1.54 www 5239: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5240: my $courseid=$2;
5241: my $roleid=$1.'.'.$2;
1.92 www 5242: $courseid=~s/^\///;
1.54 www 5243: my $expiretime=600;
1.620 albertel 5244: if ($env{'request.role'} eq $roleid) {
1.54 www 5245: $expiretime=120;
5246: }
5247: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5248: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5249: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5250: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5251: }
1.620 albertel 5252: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5253: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5254: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5255: &log($env{'user.domain'},$env{'user.name'},
5256: $env{'user.home'},
1.57 www 5257: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5258: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5259: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5260: return '';
5261: }
5262: }
1.620 albertel 5263: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5264: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5265: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5266: &log($env{'user.domain'},$env{'user.name'},
5267: $env{'user.home'},
1.57 www 5268: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5269: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5270: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5271: return '';
5272: }
5273: }
5274: }
1.29 www 5275: }
1.52 www 5276: }
5277:
5278: #
5279: # Rest of the restrictions depend on selected course
5280: #
5281:
1.620 albertel 5282: unless ($env{'request.course.id'}) {
1.766 albertel 5283: if ($thisallowed eq 'A') {
5284: return 'A';
1.814 raeburn 5285: } elsif ($thisallowed eq 'B') {
5286: return 'B';
1.766 albertel 5287: } else {
5288: return '1';
5289: }
1.52 www 5290: }
1.29 www 5291:
1.52 www 5292: #
5293: # Now user is definitely in a course
5294: #
1.53 www 5295:
5296:
5297: # Course preferences
5298:
5299: if ($thisallowed=~/C/) {
1.620 albertel 5300: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5301: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5302: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5303: =~/\Q$rolecode\E/) {
1.689 albertel 5304: if ($priv ne 'pch') {
5305: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5306: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5307: $env{'request.course.id'});
5308: }
1.237 www 5309: return '';
5310: }
5311:
1.620 albertel 5312: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5313: =~/\Q$unamedom\E/) {
1.689 albertel 5314: if ($priv ne 'pch') {
5315: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5316: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5317: $env{'request.course.id'});
5318: }
1.54 www 5319: return '';
5320: }
1.53 www 5321: }
5322:
5323: # Resource preferences
5324:
5325: if ($thisallowed=~/R/) {
1.620 albertel 5326: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5327: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5328: if ($priv ne 'pch') {
5329: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5330: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5331: }
5332: return '';
1.54 www 5333: }
1.53 www 5334: }
1.30 www 5335:
1.246 www 5336: # Restricted by state or randomout?
1.30 www 5337:
1.52 www 5338: if ($thisallowed=~/X/) {
1.620 albertel 5339: if ($env{'acc.randomout'}) {
1.579 albertel 5340: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5341: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5342: return '';
5343: }
1.247 www 5344: }
5345: if (&condval($statecond)) {
1.52 www 5346: return '2';
5347: } else {
5348: return '';
5349: }
5350: }
1.30 www 5351:
1.766 albertel 5352: if ($thisallowed eq 'A') {
5353: return 'A';
1.814 raeburn 5354: } elsif ($thisallowed eq 'B') {
5355: return 'B';
1.766 albertel 5356: }
1.52 www 5357: return 'F';
1.232 www 5358: }
5359:
1.710 albertel 5360: sub split_uri_for_cond {
5361: my $uri=&deversion(&declutter(shift));
5362: my @uriparts=split(/\//,$uri);
5363: my $filename=pop(@uriparts);
5364: my $pathname=join('/',@uriparts);
5365: return ($pathname,$filename);
5366: }
1.232 www 5367: # --------------------------------------------------- Is a resource on the map?
5368:
5369: sub is_on_map {
1.710 albertel 5370: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5371: #Trying to find the conditional for the file
1.620 albertel 5372: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5373: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5374: if ($match) {
1.289 bowersj2 5375: return (1,$1);
5376: } else {
1.434 www 5377: return (0,0);
1.289 bowersj2 5378: }
1.12 www 5379: }
5380:
1.427 www 5381: # --------------------------------------------------------- Get symb from alias
5382:
5383: sub get_symb_from_alias {
5384: my $symb=shift;
5385: my ($map,$resid,$url)=&decode_symb($symb);
5386: # Already is a symb
5387: if ($url) { return $symb; }
5388: # Must be an alias
5389: my $aliassymb='';
5390: my %bighash;
1.620 albertel 5391: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5392: &GDBM_READER(),0640)) {
5393: my $rid=$bighash{'mapalias_'.$symb};
5394: if ($rid) {
5395: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5396: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5397: $resid,$bighash{'src_'.$rid});
1.427 www 5398: }
5399: untie %bighash;
5400: }
5401: return $aliassymb;
5402: }
5403:
1.12 www 5404: # ----------------------------------------------------------------- Define Role
5405:
5406: sub definerole {
5407: if (allowed('mcr','/')) {
5408: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5409: foreach my $role (split(':',$sysrole)) {
5410: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5411: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5412: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5413: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5414: return "refused:s:$crole&$cqual";
5415: }
5416: }
1.191 harris41 5417: }
1.800 albertel 5418: foreach my $role (split(':',$domrole)) {
5419: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5420: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5421: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5422: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5423: return "refused:d:$crole&$cqual";
5424: }
5425: }
1.191 harris41 5426: }
1.800 albertel 5427: foreach my $role (split(':',$courole)) {
5428: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5429: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5430: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5431: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5432: return "refused:c:$crole&$cqual";
5433: }
5434: }
1.191 harris41 5435: }
1.620 albertel 5436: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5437: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5438: "rolesdef_$rolename=".
5439: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5440: return reply($command,$env{'user.home'});
1.12 www 5441: } else {
5442: return 'refused';
5443: }
1.105 harris41 5444: }
5445:
5446: # ---------------- Make a metadata query against the network of library servers
5447:
5448: sub metadata_query {
1.244 matthew 5449: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5450: my %rhash;
1.845 albertel 5451: my %libserv = &all_library();
1.244 matthew 5452: my @server_list = (defined($server_array) ? @$server_array
5453: : keys(%libserv) );
5454: for my $server (@server_list) {
1.118 harris41 5455: unless ($custom or $customshow) {
5456: my $reply=&reply("querysend:".&escape($query),$server);
5457: $rhash{$server}=$reply;
5458: }
5459: else {
5460: my $reply=&reply("querysend:".&escape($query).':'.
5461: &escape($custom).':'.&escape($customshow),
5462: $server);
5463: $rhash{$server}=$reply;
5464: }
1.112 harris41 5465: }
1.118 harris41 5466: return \%rhash;
1.240 www 5467: }
5468:
5469: # ----------------------------------------- Send log queries and wait for reply
5470:
5471: sub log_query {
5472: my ($uname,$udom,$query,%filters)=@_;
5473: my $uhome=&homeserver($uname,$udom);
5474: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5475: my $uhost=&hostname($uhome);
1.800 albertel 5476: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5477: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5478: $uhome);
1.479 albertel 5479: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5480: return get_query_reply($queryid);
5481: }
5482:
1.818 raeburn 5483: # -------------------------- Update MySQL table for portfolio file
5484:
5485: sub update_portfolio_table {
1.821 raeburn 5486: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5487: if ($group ne '') {
5488: $file_name =~s /^\Q$group\E//;
5489: }
1.818 raeburn 5490: my $homeserver = &homeserver($uname,$udom);
5491: my $queryid=
1.821 raeburn 5492: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5493: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5494: my $reply = &get_query_reply($queryid);
5495: return $reply;
5496: }
5497:
1.899 raeburn 5498: # -------------------------- Update MySQL allusers table
5499:
5500: sub update_allusers_table {
5501: my ($uname,$udom,$names) = @_;
5502: my $homeserver = &homeserver($uname,$udom);
5503: my $queryid=
5504: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5505: 'lastname='.&escape($names->{'lastname'}).'%%'.
5506: 'firstname='.&escape($names->{'firstname'}).'%%'.
5507: 'middlename='.&escape($names->{'middlename'}).'%%'.
5508: 'generation='.&escape($names->{'generation'}).'%%'.
5509: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5510: 'id='.&escape($names->{'id'}),$homeserver);
5511: my $reply = &get_query_reply($queryid);
5512: return $reply;
5513: }
5514:
1.508 raeburn 5515: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5516:
5517: sub fetch_enrollment_query {
1.511 raeburn 5518: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5519: my $homeserver;
1.547 raeburn 5520: my $maxtries = 1;
1.508 raeburn 5521: if ($context eq 'automated') {
5522: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5523: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5524: } else {
5525: $homeserver = &homeserver($cnum,$dom);
5526: }
1.838 albertel 5527: my $host=&hostname($homeserver);
1.506 raeburn 5528: my $cmd = '';
1.1000 raeburn 5529: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5530: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5531: }
5532: $cmd =~ s/%%$//;
5533: $cmd = &escape($cmd);
5534: my $query = 'fetchenrollment';
1.620 albertel 5535: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5536: unless ($queryid=~/^\Q$host\E\_/) {
5537: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5538: return 'error: '.$queryid;
5539: }
1.506 raeburn 5540: my $reply = &get_query_reply($queryid);
1.547 raeburn 5541: my $tries = 1;
5542: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5543: $reply = &get_query_reply($queryid);
5544: $tries ++;
5545: }
1.526 raeburn 5546: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5547: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5548: } else {
1.901 albertel 5549: my @responses = split(/:/,$reply);
1.515 raeburn 5550: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5551: foreach my $line (@responses) {
5552: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5553: $$replyref{$key} = $value;
5554: }
5555: } else {
1.506 raeburn 5556: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5557: foreach my $line (@responses) {
5558: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5559: $$replyref{$key} = $value;
5560: if ($value > 0) {
1.800 albertel 5561: foreach my $item (@{$$affiliatesref{$key}}) {
5562: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5563: my $destname = $pathname.'/'.$filename;
5564: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5565: if ($xml_classlist =~ /^error/) {
5566: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5567: } else {
1.506 raeburn 5568: if ( open(FILE,">$destname") ) {
5569: print FILE &unescape($xml_classlist);
5570: close(FILE);
1.526 raeburn 5571: } else {
5572: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5573: }
5574: }
5575: }
5576: }
5577: }
5578: }
5579: return 'ok';
5580: }
5581: return 'error';
5582: }
5583:
1.242 www 5584: sub get_query_reply {
5585: my $queryid=shift;
1.240 www 5586: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5587: my $reply='';
5588: for (1..100) {
5589: sleep 2;
5590: if (-e $replyfile.'.end') {
1.448 albertel 5591: if (open(my $fh,$replyfile)) {
1.904 albertel 5592: $reply = join('',<$fh>);
5593: close($fh);
1.240 www 5594: } else { return 'error: reply_file_error'; }
1.242 www 5595: return &unescape($reply);
5596: }
1.240 www 5597: }
1.242 www 5598: return 'timeout:'.$queryid;
1.240 www 5599: }
5600:
5601: sub courselog_query {
1.241 www 5602: #
5603: # possible filters:
5604: # url: url or symb
5605: # username
5606: # domain
5607: # action: view, submit, grade
5608: # start: timestamp
5609: # end: timestamp
5610: #
1.240 www 5611: my (%filters)=@_;
1.620 albertel 5612: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5613: if ($filters{'url'}) {
5614: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5615: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5616: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5617: }
1.620 albertel 5618: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5619: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5620: return &log_query($cname,$cdom,'courselog',%filters);
5621: }
5622:
5623: sub userlog_query {
1.858 raeburn 5624: #
5625: # possible filters:
5626: # action: log check role
5627: # start: timestamp
5628: # end: timestamp
5629: #
1.240 www 5630: my ($uname,$udom,%filters)=@_;
5631: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5632: }
5633:
1.506 raeburn 5634: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5635:
5636: sub auto_run {
1.508 raeburn 5637: my ($cnum,$cdom) = @_;
1.876 raeburn 5638: my $response = 0;
5639: my $settings;
5640: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5641: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5642: $settings = $domconfig{'autoenroll'};
5643: if ($settings->{'run'} eq '1') {
5644: $response = 1;
5645: }
5646: } else {
1.934 raeburn 5647: my $homeserver;
5648: if (&is_course($cdom,$cnum)) {
5649: $homeserver = &homeserver($cnum,$cdom);
5650: } else {
5651: $homeserver = &domain($cdom,'primary');
5652: }
5653: if ($homeserver ne 'no_host') {
5654: $response = &reply('autorun:'.$cdom,$homeserver);
5655: }
1.876 raeburn 5656: }
1.506 raeburn 5657: return $response;
5658: }
1.776 albertel 5659:
1.506 raeburn 5660: sub auto_get_sections {
1.508 raeburn 5661: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5662: my $homeserver;
5663: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5664: $homeserver = &homeserver($cnum,$cdom);
5665: }
5666: if (!defined($homeserver)) {
5667: if ($cdom =~ /^$match_domain$/) {
5668: $homeserver = &domain($cdom,'primary');
5669: }
5670: }
5671: my @secs;
5672: if (defined($homeserver)) {
5673: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5674: unless ($response eq 'refused') {
5675: @secs = split(/:/,$response);
5676: }
1.506 raeburn 5677: }
5678: return @secs;
5679: }
1.776 albertel 5680:
1.506 raeburn 5681: sub auto_new_course {
1.508 raeburn 5682: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5683: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5684: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5685: return $response;
5686: }
1.776 albertel 5687:
1.506 raeburn 5688: sub auto_validate_courseID {
1.508 raeburn 5689: my ($cnum,$cdom,$inst_course_id) = @_;
5690: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5691: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5692: return $response;
5693: }
1.776 albertel 5694:
1.1007 raeburn 5695: sub auto_validate_instcode {
1.1020 raeburn 5696: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5697: my ($homeserver,$response);
5698: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5699: $homeserver = &homeserver($cnum,$cdom);
5700: }
5701: if (!defined($homeserver)) {
5702: if ($cdom =~ /^$match_domain$/) {
5703: $homeserver = &domain($cdom,'primary');
5704: }
5705: }
5706: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020 raeburn 5707: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5708: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5709: return ($outcome,$description);
1.1007 raeburn 5710: }
5711:
1.506 raeburn 5712: sub auto_create_password {
1.873 raeburn 5713: my ($cnum,$cdom,$authparam,$udom) = @_;
5714: my ($homeserver,$response);
1.506 raeburn 5715: my $create_passwd = 0;
5716: my $authchk = '';
1.873 raeburn 5717: if ($udom =~ /^$match_domain$/) {
5718: $homeserver = &domain($udom,'primary');
5719: }
5720: if ($homeserver eq '') {
5721: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5722: $homeserver = &homeserver($cnum,$cdom);
5723: }
5724: }
5725: if ($homeserver eq '') {
5726: $authchk = 'nodomain';
1.506 raeburn 5727: } else {
1.873 raeburn 5728: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5729: if ($response eq 'refused') {
5730: $authchk = 'refused';
5731: } else {
1.901 albertel 5732: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5733: }
1.506 raeburn 5734: }
5735: return ($authparam,$create_passwd,$authchk);
5736: }
5737:
1.706 raeburn 5738: sub auto_photo_permission {
5739: my ($cnum,$cdom,$students) = @_;
5740: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5741: my ($outcome,$perm_reqd,$conditions) =
5742: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5743: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5744: return (undef,undef);
5745: }
1.706 raeburn 5746: return ($outcome,$perm_reqd,$conditions);
5747: }
5748:
5749: sub auto_checkphotos {
5750: my ($uname,$udom,$pid) = @_;
5751: my $homeserver = &homeserver($uname,$udom);
5752: my ($result,$resulttype);
5753: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5754: &escape($uname).':'.&escape($pid),
5755: $homeserver));
1.709 albertel 5756: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5757: return (undef,undef);
5758: }
1.706 raeburn 5759: if ($outcome) {
5760: ($result,$resulttype) = split(/:/,$outcome);
5761: }
5762: return ($result,$resulttype);
5763: }
5764:
5765: sub auto_photochoice {
5766: my ($cnum,$cdom) = @_;
5767: my $homeserver = &homeserver($cnum,$cdom);
5768: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5769: &escape($cdom),
5770: $homeserver)));
1.709 albertel 5771: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5772: return (undef,undef);
5773: }
1.706 raeburn 5774: return ($update,$comment);
5775: }
5776:
5777: sub auto_photoupdate {
5778: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5779: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5780: my $host=&hostname($homeserver);
1.706 raeburn 5781: my $cmd = '';
5782: my $maxtries = 1;
1.800 albertel 5783: foreach my $affiliate (keys(%{$affiliatesref})) {
5784: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5785: }
5786: $cmd =~ s/%%$//;
5787: $cmd = &escape($cmd);
5788: my $query = 'institutionalphotos';
5789: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5790: unless ($queryid=~/^\Q$host\E\_/) {
5791: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5792: return 'error: '.$queryid;
5793: }
5794: my $reply = &get_query_reply($queryid);
5795: my $tries = 1;
5796: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5797: $reply = &get_query_reply($queryid);
5798: $tries ++;
5799: }
5800: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5801: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5802: } else {
5803: my @responses = split(/:/,$reply);
5804: my $outcome = shift(@responses);
5805: foreach my $item (@responses) {
5806: my ($key,$value) = split(/=/,$item);
5807: $$photo{$key} = $value;
5808: }
5809: return $outcome;
5810: }
5811: return 'error';
5812: }
5813:
1.521 raeburn 5814: sub auto_instcode_format {
1.793 albertel 5815: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5816: $cat_order) = @_;
1.521 raeburn 5817: my $courses = '';
1.772 raeburn 5818: my @homeservers;
1.521 raeburn 5819: if ($caller eq 'global') {
1.841 albertel 5820: my %servers = &get_servers($codedom,'library');
5821: foreach my $tryserver (keys(%servers)) {
5822: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5823: push(@homeservers,$tryserver);
5824: }
1.584 raeburn 5825: }
1.1022 raeburn 5826: } elsif ($caller eq 'requests') {
5827: if ($codedom =~ /^$match_domain$/) {
5828: my $chome = &domain($codedom,'primary');
5829: unless ($chome eq 'no_host') {
5830: push(@homeservers,$chome);
5831: }
5832: }
1.521 raeburn 5833: } else {
1.772 raeburn 5834: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5835: }
1.793 albertel 5836: foreach my $code (keys(%{$instcodes})) {
5837: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5838: }
5839: chop($courses);
1.772 raeburn 5840: my $ok_response = 0;
5841: my $response;
5842: while (@homeservers > 0 && $ok_response == 0) {
5843: my $server = shift(@homeservers);
5844: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5845: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5846: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5847: split(/:/,$response);
1.772 raeburn 5848: %{$codes} = (%{$codes},&str2hash($codes_str));
5849: push(@{$codetitles},&str2array($codetitles_str));
5850: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5851: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5852: $ok_response = 1;
5853: }
5854: }
5855: if ($ok_response) {
1.521 raeburn 5856: return 'ok';
1.772 raeburn 5857: } else {
5858: return $response;
1.521 raeburn 5859: }
5860: }
5861:
1.792 raeburn 5862: sub auto_instcode_defaults {
5863: my ($domain,$returnhash,$code_order) = @_;
5864: my @homeservers;
1.841 albertel 5865:
5866: my %servers = &get_servers($domain,'library');
5867: foreach my $tryserver (keys(%servers)) {
5868: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5869: push(@homeservers,$tryserver);
5870: }
1.792 raeburn 5871: }
1.841 albertel 5872:
1.792 raeburn 5873: my $response;
1.841 albertel 5874: foreach my $server (@homeservers) {
1.792 raeburn 5875: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5876: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5877:
5878: foreach my $pair (split(/\&/,$response)) {
5879: my ($name,$value)=split(/\=/,$pair);
5880: if ($name eq 'code_order') {
5881: @{$code_order} = split(/\&/,&unescape($value));
5882: } else {
5883: $returnhash->{&unescape($name)}=&unescape($value);
5884: }
5885: }
5886: return 'ok';
1.792 raeburn 5887: }
1.841 albertel 5888:
5889: return $response;
1.1003 raeburn 5890: }
5891:
5892: sub auto_possible_instcodes {
1.1007 raeburn 5893: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5894: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5895: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5896: return;
5897: }
1.1003 raeburn 5898: my (@homeservers,$uhome);
5899: if (defined(&domain($domain,'primary'))) {
5900: $uhome=&domain($domain,'primary');
5901: push(@homeservers,&domain($domain,'primary'));
5902: } else {
5903: my %servers = &get_servers($domain,'library');
5904: foreach my $tryserver (keys(%servers)) {
5905: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5906: push(@homeservers,$tryserver);
5907: }
5908: }
5909: }
5910: my $response;
5911: foreach my $server (@homeservers) {
5912: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5913: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5914: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5915: split(':',$response);
5916: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5917: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5918: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5919: my ($name,$value)=split('=',$item);
5920: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5921: }
5922: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5923: my ($name,$value)=split('=',$item);
5924: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5925: }
5926: return 'ok';
5927: }
5928: return $response;
5929: }
1.792 raeburn 5930:
1.1010 raeburn 5931: sub auto_courserequest_checks {
5932: my ($dom) = @_;
1.1020 raeburn 5933: my ($homeserver,%validations);
5934: if ($dom =~ /^$match_domain$/) {
5935: $homeserver = &domain($dom,'primary');
5936: }
5937: unless ($homeserver eq 'no_host') {
5938: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5939: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5940: my @items = split(/&/,$response);
5941: foreach my $item (@items) {
5942: my ($key,$value) = split('=',$item);
5943: $validations{&unescape($key)} = &thaw_unescape($value);
5944: }
5945: }
5946: }
1.1010 raeburn 5947: return %validations;
5948: }
5949:
1.1020 raeburn 5950: sub auto_courserequest_validation {
5951: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5952: my ($homeserver,$response);
5953: if ($dom =~ /^$match_domain$/) {
5954: $homeserver = &domain($dom,'primary');
5955: }
5956: unless ($homeserver eq 'no_host') {
1.1021 raeburn 5957:
1.1020 raeburn 5958: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 5959: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 5960: ':'.&escape($instcode).':'.&escape($instseclist),
5961: $homeserver));
5962: }
5963: return $response;
5964: }
5965:
1.777 albertel 5966: sub auto_validate_class_sec {
1.918 raeburn 5967: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5968: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5969: my $ownerlist;
5970: if (ref($owners) eq 'ARRAY') {
5971: $ownerlist = join(',',@{$owners});
5972: } else {
5973: $ownerlist = $owners;
5974: }
1.773 raeburn 5975: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5976: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5977: return $response;
5978: }
5979:
1.679 raeburn 5980: # ------------------------------------------------------- Course Group routines
5981:
5982: sub get_coursegroups {
1.809 raeburn 5983: my ($cdom,$cnum,$group,$namespace) = @_;
5984: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5985: }
5986:
1.679 raeburn 5987: sub modify_coursegroup {
5988: my ($cdom,$cnum,$groupsettings) = @_;
5989: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5990: }
5991:
1.809 raeburn 5992: sub toggle_coursegroup_status {
5993: my ($cdom,$cnum,$group,$action) = @_;
5994: my ($from_namespace,$to_namespace);
5995: if ($action eq 'delete') {
5996: $from_namespace = 'coursegroups';
5997: $to_namespace = 'deleted_groups';
5998: } else {
5999: $from_namespace = 'deleted_groups';
6000: $to_namespace = 'coursegroups';
6001: }
6002: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6003: if (my $tmp = &error(%curr_group)) {
6004: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6005: return ('read error',$tmp);
6006: } else {
6007: my %savedsettings = %curr_group;
1.809 raeburn 6008: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6009: my $deloutcome;
6010: if ($result eq 'ok') {
1.809 raeburn 6011: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6012: } else {
6013: return ('write error',$result);
6014: }
6015: if ($deloutcome eq 'ok') {
6016: return 'ok';
6017: } else {
6018: return ('delete error',$deloutcome);
6019: }
6020: }
6021: }
6022:
1.679 raeburn 6023: sub modify_group_roles {
1.957 raeburn 6024: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6025: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6026: my $role = 'gr/'.&escape($userprivs);
6027: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6028: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6029: if ($result eq 'ok') {
6030: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6031: }
1.679 raeburn 6032: return $result;
6033: }
6034:
6035: sub modify_coursegroup_membership {
6036: my ($cdom,$cnum,$membership) = @_;
6037: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6038: return $result;
6039: }
6040:
1.682 raeburn 6041: sub get_active_groups {
6042: my ($udom,$uname,$cdom,$cnum) = @_;
6043: my $now = time;
6044: my %groups = ();
6045: foreach my $key (keys(%env)) {
1.811 albertel 6046: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6047: my ($start,$end) = split(/\./,$env{$key});
6048: if (($end!=0) && ($end<$now)) { next; }
6049: if (($start!=0) && ($start>$now)) { next; }
6050: if ($1 eq $cdom && $2 eq $cnum) {
6051: $groups{$3} = $env{$key} ;
6052: }
6053: }
6054: }
6055: return %groups;
6056: }
6057:
1.683 raeburn 6058: sub get_group_membership {
6059: my ($cdom,$cnum,$group) = @_;
6060: return(&dump('groupmembership',$cdom,$cnum,$group));
6061: }
6062:
6063: sub get_users_groups {
6064: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6065: my @usersgroups;
1.683 raeburn 6066: my $cachetime=1800;
6067:
6068: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6069: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6070: if (defined($cached)) {
1.734 albertel 6071: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6072: } else {
6073: $grouplist = '';
1.816 raeburn 6074: my $courseurl = &courseid_to_courseurl($courseid);
6075: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6076: my $access_end = $env{'course.'.$courseid.
6077: '.default_enrollment_end_date'};
6078: my $now = time;
6079: foreach my $key (keys(%roleshash)) {
6080: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6081: my $group = $1;
6082: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6083: my $start = $2;
6084: my $end = $1;
6085: if ($start == -1) { next; } # deleted from group
6086: if (($start!=0) && ($start>$now)) { next; }
6087: if (($end!=0) && ($end<$now)) {
6088: if ($access_end && $access_end < $now) {
6089: if ($access_end - $end < 86400) {
6090: push(@usersgroups,$group);
1.733 raeburn 6091: }
6092: }
1.817 raeburn 6093: next;
1.733 raeburn 6094: }
1.817 raeburn 6095: push(@usersgroups,$group);
1.683 raeburn 6096: }
6097: }
6098: }
1.817 raeburn 6099: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6100: $grouplist = join(':',@usersgroups);
6101: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6102: }
1.733 raeburn 6103: return @usersgroups;
1.683 raeburn 6104: }
6105:
6106: sub devalidate_getgroups_cache {
6107: my ($udom,$uname,$cdom,$cnum)=@_;
6108: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6109:
1.683 raeburn 6110: my $hashid="$udom:$uname:$courseid";
6111: &devalidate_cache_new('getgroups',$hashid);
6112: }
6113:
1.12 www 6114: # ------------------------------------------------------------------ Plain Text
6115:
6116: sub plaintext {
1.988 raeburn 6117: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6118: if ($short =~ m{^cr/}) {
1.758 albertel 6119: return (split('/',$short))[-1];
6120: }
1.742 raeburn 6121: if (!defined($cid)) {
6122: $cid = $env{'request.course.id'};
6123: }
6124: my %rolenames = (
1.1008 raeburn 6125: Course => 'std',
6126: Community => 'alt1',
1.742 raeburn 6127: );
1.1037 raeburn 6128: if ($cid ne '') {
6129: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6130: unless ($forcedefault) {
6131: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6132: &Apache::lonlocal::mt_escape(\$roletext);
6133: return &Apache::lonlocal::mt($roletext);
6134: }
6135: }
6136: }
6137: if ((defined($type)) && (defined($rolenames{$type})) &&
6138: (defined($rolenames{$type})) &&
6139: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6140: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6141: } elsif ($cid ne '') {
6142: my $crstype = $env{'course.'.$cid.'.type'};
6143: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6144: (defined($prp{$short}{$rolenames{$crstype}}))) {
6145: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6146: }
1.742 raeburn 6147: }
1.1037 raeburn 6148: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6149: }
6150:
6151: # ----------------------------------------------------------------- Assign Role
6152:
6153: sub assignrole {
1.957 raeburn 6154: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6155: $context)=@_;
1.21 www 6156: my $mrole;
6157: if ($role =~ /^cr\//) {
1.393 www 6158: my $cwosec=$url;
1.811 albertel 6159: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6160: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6161: my $refused = 1;
6162: if ($context eq 'requestcourses') {
6163: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6164: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6165: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6166: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6167: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6168: if ($crsenv{'internal.courseowner'} eq
6169: $env{'user.name'}.':'.$env{'user.domain'}) {
6170: $refused = '';
6171: }
6172: }
6173: }
6174: }
6175: }
6176: if ($refused) {
6177: &logthis('Refused custom assignrole: '.
6178: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6179: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6180: return 'refused';
6181: }
1.104 www 6182: }
1.21 www 6183: $mrole='cr';
1.678 raeburn 6184: } elsif ($role =~ /^gr\//) {
6185: my $cwogrp=$url;
1.811 albertel 6186: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6187: unless (&allowed('mdg',$cwogrp)) {
6188: &logthis('Refused group assignrole: '.
6189: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6190: $env{'user.name'}.' at '.$env{'user.domain'});
6191: return 'refused';
6192: }
6193: $mrole='gr';
1.21 www 6194: } else {
1.82 www 6195: my $cwosec=$url;
1.811 albertel 6196: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6197: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6198: my $refused;
6199: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6200: if (!(&allowed('c'.$role,$url))) {
6201: $refused = 1;
6202: }
6203: } else {
6204: $refused = 1;
6205: }
1.947 raeburn 6206: if ($refused) {
1.1045 raeburn 6207: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6208: if (!$selfenroll && $context eq 'course') {
6209: my %crsenv;
6210: if ($role eq 'cc' || $role eq 'co') {
6211: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6212: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6213: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6214: if ($crsenv{'internal.courseowner'} eq
6215: $env{'user.name'}.':'.$env{'user.domain'}) {
6216: $refused = '';
6217: }
6218: }
6219: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6220: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6221: if ($crsenv{'internal.courseowner'} eq
6222: $env{'user.name'}.':'.$env{'user.domain'}) {
6223: $refused = '';
6224: }
6225: }
6226: }
6227: }
6228: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6229: $refused = '';
1.1017 raeburn 6230: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6231: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6232: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6233: my $wrongcc;
6234: if ($cnum =~ /^$match_community$/) {
6235: $wrongcc = 1 if ($role eq 'cc');
6236: } else {
6237: $wrongcc = 1 if ($role eq 'co');
6238: }
6239: unless ($wrongcc) {
6240: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6241: if ($crsenv{'internal.courseowner'} eq
6242: $env{'user.name'}.':'.$env{'user.domain'}) {
6243: $refused = '';
6244: }
1.1017 raeburn 6245: }
6246: }
6247: }
6248: if ($refused) {
1.947 raeburn 6249: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6250: ' '.$role.' '.$end.' '.$start.' by '.
6251: $env{'user.name'}.' at '.$env{'user.domain'});
6252: return 'refused';
6253: }
1.932 raeburn 6254: }
1.104 www 6255: }
1.21 www 6256: $mrole=$role;
6257: }
1.620 albertel 6258: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6259: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6260: if ($end) { $command.='_'.$end; }
1.21 www 6261: if ($start) {
6262: if ($end) {
1.81 www 6263: $command.='_'.$start;
1.21 www 6264: } else {
1.81 www 6265: $command.='_0_'.$start;
1.21 www 6266: }
6267: }
1.739 raeburn 6268: my $origstart = $start;
6269: my $origend = $end;
1.957 raeburn 6270: my $delflag;
1.357 www 6271: # actually delete
6272: if ($deleteflag) {
1.373 www 6273: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6274: # modify command to delete the role
1.620 albertel 6275: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6276: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6277: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6278: # set start and finish to negative values for userrolelog
6279: $start=-1;
6280: $end=-1;
1.957 raeburn 6281: $delflag = 1;
1.357 www 6282: }
6283: }
6284: # send command
1.349 www 6285: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6286: # log new user role if status is ok
1.349 www 6287: if ($answer eq 'ok') {
1.663 raeburn 6288: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6289: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6290: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6291: unless ($role =~ /^gr/) {
6292: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6293: $origstart,$selfenroll,$context);
1.739 raeburn 6294: }
1.1053 raeburn 6295: if ($role eq 'cc') {
6296: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6297: }
1.349 www 6298: }
6299: return $answer;
1.169 harris41 6300: }
6301:
1.1053 raeburn 6302: sub autoupdate_coowners {
6303: my ($url,$end,$start,$uname,$udom) = @_;
6304: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6305: if (($cdom ne '') && ($cnum ne '')) {
6306: my $now = time;
6307: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6308: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6309: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6310: my $instcode = $coursehash{'internal.coursecode'};
6311: if ($instcode ne '') {
1.1056 raeburn 6312: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6313: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6314: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6315: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6316: if ($result eq 'valid') {
6317: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6318: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6319: push(@newcoowners,$coowner);
6320: }
6321: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6322: push(@newcoowners,$uname.':'.$udom);
6323: }
6324: @newcoowners = sort(@newcoowners);
6325: } else {
6326: push(@newcoowners,$uname.':'.$udom);
6327: }
6328: } else {
6329: if ($coursehash{'internal.co-owners'}) {
6330: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6331: unless ($coowner eq $uname.':'.$udom) {
6332: push(@newcoowners,$coowner);
6333: }
6334: }
6335: unless (@newcoowners > 0) {
6336: $delcoowners = 1;
6337: $coowners = '';
6338: }
6339: }
6340: }
6341: if (@newcoowners || $delcoowners) {
6342: &store_coowners($cdom,$cnum,$coursehash{'home'},
6343: $delcoowners,@newcoowners);
6344: }
6345: }
6346: }
6347: }
6348: }
6349: }
6350: }
6351:
6352: sub store_coowners {
6353: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6354: my $cid = $cdom.'_'.$cnum;
6355: my ($coowners,$delresult,$putresult);
6356: if (@newcoowners) {
6357: $coowners = join(',',@newcoowners);
6358: my %coownershash = (
6359: 'internal.co-owners' => $coowners,
6360: );
6361: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6362: if ($putresult eq 'ok') {
6363: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6364: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6365: }
6366: }
6367: }
6368: if ($delcoowners) {
6369: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6370: if ($delresult eq 'ok') {
6371: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6372: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6373: }
6374: }
6375: }
6376: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6377: my %crsinfo =
6378: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6379: if (ref($crsinfo{$cid}) eq 'HASH') {
6380: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6381: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6382: }
6383: }
6384: }
6385:
1.169 harris41 6386: # -------------------------------------------------- Modify user authentication
1.197 www 6387: # Overrides without validation
6388:
1.169 harris41 6389: sub modifyuserauth {
6390: my ($udom,$uname,$umode,$upass)=@_;
6391: my $uhome=&homeserver($uname,$udom);
1.197 www 6392: unless (&allowed('mau',$udom)) { return 'refused'; }
6393: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6394: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6395: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6396: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6397: &escape($upass),$uhome);
1.620 albertel 6398: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6399: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6400: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6401: &log($udom,,$uname,$uhome,
1.620 albertel 6402: 'Authentication changed by '.$env{'user.domain'}.', '.
6403: $env{'user.name'}.', '.$umode.
1.197 www 6404: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6405: unless ($reply eq 'ok') {
1.197 www 6406: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6407: return 'error: '.$reply;
6408: }
1.170 harris41 6409: return 'ok';
1.80 www 6410: }
6411:
1.81 www 6412: # --------------------------------------------------------------- Modify a user
1.80 www 6413:
1.81 www 6414: sub modifyuser {
1.206 matthew 6415: my ($udom, $uname, $uid,
6416: $umode, $upass, $first,
6417: $middle, $last, $gene,
1.1058 raeburn 6418: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6419: $udom= &LONCAPA::clean_domain($udom);
6420: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6421: my $showcandelete = 'none';
6422: if (ref($candelete) eq 'ARRAY') {
6423: if (@{$candelete} > 0) {
6424: $showcandelete = join(', ',@{$candelete});
6425: }
6426: }
1.81 www 6427: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6428: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6429: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6430: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6431: ' desiredhome not specified').
1.620 albertel 6432: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6433: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6434: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6435: # ----------------------------------------------------------------- Create User
1.406 albertel 6436: if (($uhome eq 'no_host') &&
6437: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6438: my $unhome='';
1.844 albertel 6439: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6440: $unhome = $desiredhome;
1.620 albertel 6441: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6442: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6443: } else { # load balancing routine for determining $unhome
1.81 www 6444: my $loadm=10000000;
1.841 albertel 6445: my %servers = &get_servers($udom,'library');
6446: foreach my $tryserver (keys(%servers)) {
6447: my $answer=reply('load',$tryserver);
6448: if (($answer=~/\d+/) && ($answer<$loadm)) {
6449: $loadm=$answer;
6450: $unhome=$tryserver;
6451: }
1.80 www 6452: }
6453: }
6454: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6455: return 'error: unable to find a home server for '.$uname.
6456: ' in domain '.$udom;
1.80 www 6457: }
6458: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6459: &escape($upass),$unhome);
6460: unless ($reply eq 'ok') {
6461: return 'error: '.$reply;
6462: }
1.230 stredwic 6463: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6464: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6465: return 'error: unable verify users home machine.';
1.80 www 6466: }
1.209 matthew 6467: } # End of creation of new user
1.80 www 6468: # ---------------------------------------------------------------------- Add ID
6469: if ($uid) {
6470: $uid=~tr/A-Z/a-z/;
6471: my %uidhash=&idrget($udom,$uname);
1.196 www 6472: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6473: && (!$forceid)) {
1.80 www 6474: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6475: return 'error: user id "'.$uid.'" does not match '.
6476: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6477: }
6478: } else {
6479: &idput($udom,($uname => $uid));
6480: }
6481: }
6482: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6483: my @tmp=&get('environment',
1.899 raeburn 6484: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6485: 'permanentemail','inststatus'],
1.134 albertel 6486: $udom,$uname);
1.313 matthew 6487: my %names;
6488: if ($tmp[0] =~ m/^error:.*/) {
6489: %names=();
6490: } else {
6491: %names = @tmp;
6492: }
1.388 www 6493: #
1.1058 raeburn 6494: # If name, email and/or uid are blank (e.g., because an uploaded file
6495: # of users did not contain them), do not overwrite existing values
6496: # unless field is in $candelete array ref.
6497: #
6498:
6499: my @fields = ('firstname','middlename','lastname','generation',
6500: 'permanentemail','id');
6501: my %newvalues;
6502: if (ref($candelete) eq 'ARRAY') {
6503: foreach my $field (@fields) {
6504: if (grep(/^\Q$field\E$/,@{$candelete})) {
6505: if ($field eq 'firstname') {
6506: $names{$field} = $first;
6507: } elsif ($field eq 'middlename') {
6508: $names{$field} = $middle;
6509: } elsif ($field eq 'lastname') {
6510: $names{$field} = $last;
6511: } elsif ($field eq 'generation') {
6512: $names{$field} = $gene;
6513: } elsif ($field eq 'permanentemail') {
6514: $names{$field} = $email;
6515: } elsif ($field eq 'id') {
6516: $names{$field} = $uid;
6517: }
6518: }
6519: }
6520: }
1.388 www 6521: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6522: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6523: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6524: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6525: if ($email) {
6526: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6527: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6528: }
1.899 raeburn 6529: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6530: if (defined($inststatus)) {
6531: $names{'inststatus'} = '';
6532: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6533: if (ref($usertypes) eq 'HASH') {
6534: my @okstatuses;
6535: foreach my $item (split(/:/,$inststatus)) {
6536: if (defined($usertypes->{$item})) {
6537: push(@okstatuses,$item);
6538: }
6539: }
6540: if (@okstatuses) {
6541: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6542: }
6543: }
6544: }
1.134 albertel 6545: my $reply = &put('environment', \%names, $udom,$uname);
6546: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6547: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6548: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6549: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6550: $umode.', '.$first.', '.$middle.', '.
6551: $last.', '.$gene.', '.$email.', '.$inststatus;
6552: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6553: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6554: } else {
6555: $logmsg .= ' during self creation';
6556: }
6557: &logthis($logmsg);
1.134 albertel 6558: return 'ok';
1.80 www 6559: }
6560:
1.81 www 6561: # -------------------------------------------------------------- Modify student
1.80 www 6562:
1.81 www 6563: sub modifystudent {
6564: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6565: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6566: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6567: if (!$cid) {
1.620 albertel 6568: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6569: return 'not_in_class';
6570: }
1.80 www 6571: }
6572: # --------------------------------------------------------------- Make the user
1.81 www 6573: my $reply=&modifyuser
1.209 matthew 6574: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6575: $desiredhome,$email,$inststatus);
1.80 www 6576: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6577: # This will cause &modify_student_enrollment to get the uid from the
6578: # students environment
6579: $uid = undef if (!$forceid);
1.455 albertel 6580: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6581: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6582: return $reply;
6583: }
6584:
6585: sub modify_student_enrollment {
1.957 raeburn 6586: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6587: my ($cdom,$cnum,$chome);
6588: if (!$cid) {
1.620 albertel 6589: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6590: return 'not_in_class';
6591: }
1.620 albertel 6592: $cdom=$env{'course.'.$cid.'.domain'};
6593: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6594: } else {
6595: ($cdom,$cnum)=split(/_/,$cid);
6596: }
1.620 albertel 6597: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6598: if (!$chome) {
1.457 raeburn 6599: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6600: }
1.455 albertel 6601: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6602: # Make sure the user exists
1.81 www 6603: my $uhome=&homeserver($uname,$udom);
6604: if (($uhome eq '') || ($uhome eq 'no_host')) {
6605: return 'error: no such user';
6606: }
1.297 matthew 6607: # Get student data if we were not given enough information
6608: if (!defined($first) || $first eq '' ||
6609: !defined($last) || $last eq '' ||
6610: !defined($uid) || $uid eq '' ||
6611: !defined($middle) || $middle eq '' ||
6612: !defined($gene) || $gene eq '') {
1.294 matthew 6613: # They did not supply us with enough data to enroll the student, so
6614: # we need to pick up more information.
1.297 matthew 6615: my %tmp = &get('environment',
1.294 matthew 6616: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6617: ,$udom,$uname);
6618:
1.800 albertel 6619: #foreach my $key (keys(%tmp)) {
6620: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6621: #}
1.294 matthew 6622: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6623: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6624: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6625: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6626: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6627: }
1.556 albertel 6628: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6629: my $reply=cput('classlist',
6630: {"$uname:$udom" =>
1.515 raeburn 6631: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6632: $cdom,$cnum);
1.81 www 6633: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6634: return 'error: '.$reply;
1.652 albertel 6635: } else {
6636: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6637: }
1.297 matthew 6638: # Add student role to user
1.83 www 6639: my $uurl='/'.$cid;
1.81 www 6640: $uurl=~s/\_/\//g;
6641: if ($usec) {
6642: $uurl.='/'.$usec;
6643: }
1.957 raeburn 6644: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6645: }
6646:
1.556 albertel 6647: sub format_name {
6648: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6649: my $name;
6650: if ($first ne 'lastname') {
6651: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6652: } else {
6653: if ($lastname=~/\S/) {
6654: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6655: $name=~s/\s+,/,/;
6656: } else {
6657: $name.= $firstname.' '.$middlename.' '.$generation;
6658: }
6659: }
6660: $name=~s/^\s+//;
6661: $name=~s/\s+$//;
6662: $name=~s/\s+/ /g;
6663: return $name;
6664: }
6665:
1.84 www 6666: # ------------------------------------------------- Write to course preferences
6667:
6668: sub writecoursepref {
6669: my ($courseid,%prefs)=@_;
6670: $courseid=~s/^\///;
6671: $courseid=~s/\_/\//g;
6672: my ($cdomain,$cnum)=split(/\//,$courseid);
6673: my $chome=homeserver($cnum,$cdomain);
6674: if (($chome eq '') || ($chome eq 'no_host')) {
6675: return 'error: no such course';
6676: }
6677: my $cstring='';
1.800 albertel 6678: foreach my $pref (keys(%prefs)) {
6679: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6680: }
1.84 www 6681: $cstring=~s/\&$//;
6682: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6683: }
6684:
6685: # ---------------------------------------------------------- Make/modify course
6686:
6687: sub createcourse {
1.741 raeburn 6688: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6689: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6690: $url=&declutter($url);
6691: my $cid='';
1.1028 raeburn 6692: if ($context eq 'requestcourses') {
6693: my $can_create = 0;
6694: my ($ownername,$ownerdom) = split(':',$course_owner);
6695: if ($udom eq $ownerdom) {
6696: if (&usertools_access($ownername,$ownerdom,$category,undef,
6697: $context)) {
6698: $can_create = 1;
6699: }
6700: } else {
6701: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6702: $category);
6703: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6704: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6705: if (@curr > 0) {
6706: my @options = qw(approval validate autolimit);
6707: my $optregex = join('|',@options);
6708: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6709: $can_create = 1;
6710: }
6711: }
6712: }
6713: }
6714: if ($can_create) {
6715: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6716: unless (&allowed('ccc',$udom)) {
6717: return 'refused';
6718: }
1.1017 raeburn 6719: }
6720: } else {
6721: return 'refused';
6722: }
1.1028 raeburn 6723: } elsif (!&allowed('ccc',$udom)) {
6724: return 'refused';
1.84 www 6725: }
1.1011 raeburn 6726: # --------------------------------------------------------------- Get Unique ID
6727: my $uname;
6728: if ($cnum =~ /^$match_courseid$/) {
6729: my $chome=&homeserver($cnum,$udom,'true');
6730: if (($chome eq '') || ($chome eq 'no_host')) {
6731: $uname = $cnum;
6732: } else {
1.1038 raeburn 6733: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6734: }
6735: } else {
1.1038 raeburn 6736: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6737: }
6738: return $uname if ($uname =~ /^error/);
6739: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6740: if (!defined($course_server)) {
6741: if (defined(&domain($udom,'primary'))) {
6742: $course_server = &domain($udom,'primary');
6743: } else {
6744: $course_server = $env{'user.home'};
6745: }
6746: }
6747: my %host_servers =
6748: &Apache::lonnet::get_servers($udom,'library');
6749: unless ($host_servers{$course_server}) {
6750: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6751: }
1.84 www 6752: # ------------------------------------------------------------- Make the course
6753: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6754: $course_server);
1.84 www 6755: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6756: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6757: if (($uhome eq '') || ($uhome eq 'no_host')) {
6758: return 'error: no such course';
6759: }
1.271 www 6760: # ----------------------------------------------------------------- Course made
1.516 raeburn 6761: # log existence
1.1029 raeburn 6762: my $now = time;
1.918 raeburn 6763: my $newcourse = {
6764: $udom.'_'.$uname => {
1.921 raeburn 6765: description => $description,
6766: inst_code => $inst_code,
6767: owner => $course_owner,
6768: type => $crstype,
1.1029 raeburn 6769: creator => $env{'user.name'}.':'.
6770: $env{'user.domain'},
6771: created => $now,
6772: context => $context,
1.918 raeburn 6773: },
6774: };
1.921 raeburn 6775: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6776: # set toplevel url
1.271 www 6777: my $topurl=$url;
6778: unless ($nonstandard) {
6779: # ------------------------------------------ For standard courses, make top url
6780: my $mapurl=&clutter($url);
1.278 www 6781: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6782: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6783: <map>
6784: <resource id="1" type="start"></resource>
6785: <resource id="2" src="$mapurl"></resource>
6786: <resource id="3" type="finish"></resource>
6787: <link index="1" from="1" to="2"></link>
6788: <link index="2" from="2" to="3"></link>
6789: </map>
6790: ENDINITMAP
6791: $topurl=&declutter(
1.638 albertel 6792: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6793: );
6794: }
6795: # ----------------------------------------------------------- Write preferences
1.84 www 6796: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6797: ('description' => $description,
6798: 'url' => $topurl,
6799: 'internal.creator' => $env{'user.name'}.':'.
6800: $env{'user.domain'},
6801: 'internal.created' => $now,
6802: 'internal.creationcontext' => $context)
6803: );
1.84 www 6804: return '/'.$udom.'/'.$uname;
6805: }
6806:
1.1011 raeburn 6807: # ------------------------------------------------------------------- Create ID
6808: sub generate_coursenum {
1.1038 raeburn 6809: my ($udom,$crstype) = @_;
1.1011 raeburn 6810: my $domdesc = &domain($udom);
6811: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 6812: my $first;
6813: if ($crstype eq 'Community') {
6814: $first = '0';
6815: } else {
6816: $first = int(1+rand(9));
6817: }
6818: my $uname=$first.
1.1011 raeburn 6819: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6820: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6821: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6822: # ----------------------------------------------- Make sure that does not exist
6823: my $uhome=&homeserver($uname,$udom,'true');
6824: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 6825: if ($crstype eq 'Community') {
6826: $first = '0';
6827: } else {
6828: $first = int(1+rand(9));
6829: }
6830: $uname=$first.
1.1011 raeburn 6831: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6832: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6833: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6834: $uhome=&homeserver($uname,$udom,'true');
6835: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6836: return 'error: unable to generate unique course-ID';
6837: }
6838: }
6839: return $uname;
6840: }
6841:
1.813 albertel 6842: sub is_course {
6843: my ($cdom,$cnum) = @_;
6844: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6845: undef,'.');
1.813 albertel 6846: if (exists($courses{$cdom.'_'.$cnum})) {
6847: return 1;
6848: }
6849: return 0;
6850: }
6851:
1.1015 raeburn 6852: sub store_userdata {
6853: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 6854: my $result;
1.1016 raeburn 6855: if ($datakey ne '') {
1.1013 raeburn 6856: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 6857: if ($udom eq '' || $uname eq '') {
6858: $udom = $env{'user.domain'};
6859: $uname = $env{'user.name'};
6860: }
6861: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 6862: if (($uhome eq '') || ($uhome eq 'no_host')) {
6863: $result = 'error: no_host';
6864: } else {
6865: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6866: $storehash->{'host'} = $perlvar{'lonHostID'};
6867:
6868: my $namevalue='';
6869: foreach my $key (keys(%{$storehash})) {
6870: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6871: }
6872: $namevalue=~s/\&$//;
6873: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 6874: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 6875: }
6876: } else {
6877: $result = 'error: data to store was not a hash reference';
6878: }
6879: } else {
6880: $result= 'error: invalid requestkey';
6881: }
6882: return $result;
6883: }
6884:
1.21 www 6885: # ---------------------------------------------------------- Assign Custom Role
6886:
6887: sub assigncustomrole {
1.957 raeburn 6888: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6889: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6890: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6891: }
6892:
6893: # ----------------------------------------------------------------- Revoke Role
6894:
6895: sub revokerole {
1.957 raeburn 6896: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6897: my $now=time;
1.965 raeburn 6898: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6899: }
6900:
6901: # ---------------------------------------------------------- Revoke Custom Role
6902:
6903: sub revokecustomrole {
1.957 raeburn 6904: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6905: my $now=time;
1.357 www 6906: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6907: $deleteflag,$selfenroll,$context);
1.17 www 6908: }
6909:
1.533 banghart 6910: # ------------------------------------------------------------ Disk usage
1.535 albertel 6911: sub diskusage {
1.955 raeburn 6912: my ($udom,$uname,$directorypath,$getpropath)=@_;
6913: $directorypath =~ s/\/$//;
6914: my $listing=&reply('du2:'.&escape($directorypath).':'
6915: .&escape($getpropath).':'.&escape($uname).':'
6916: .&escape($udom),homeserver($uname,$udom));
6917: if ($listing eq 'unknown_cmd') {
6918: if ($getpropath) {
6919: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6920: }
6921: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6922: }
1.514 albertel 6923: return $listing;
1.512 banghart 6924: }
6925:
1.566 banghart 6926: sub is_locked {
6927: my ($file_name, $domain, $user) = @_;
6928: my @check;
6929: my $is_locked;
6930: push @check, $file_name;
1.613 albertel 6931: my %locked = &get('file_permissions',\@check,
1.620 albertel 6932: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6933: my ($tmp)=keys(%locked);
6934: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6935:
1.566 banghart 6936: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6937: $is_locked = 'false';
6938: foreach my $entry (@{$locked{$file_name}}) {
6939: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6940: $is_locked = 'true';
6941: last;
1.745 raeburn 6942: }
6943: }
1.566 banghart 6944: } else {
6945: $is_locked = 'false';
6946: }
6947: }
6948:
1.759 albertel 6949: sub declutter_portfile {
6950: my ($file) = @_;
1.833 albertel 6951: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6952: return $file;
6953: }
6954:
1.559 banghart 6955: # ------------------------------------------------------------- Mark as Read Only
6956:
6957: sub mark_as_readonly {
6958: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6959: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6960: my ($tmp)=keys(%current_permissions);
6961: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6962: foreach my $file (@{$files}) {
1.759 albertel 6963: $file = &declutter_portfile($file);
1.561 banghart 6964: push(@{$current_permissions{$file}},$what);
1.559 banghart 6965: }
1.613 albertel 6966: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6967: return;
6968: }
6969:
1.572 banghart 6970: # ------------------------------------------------------------Save Selected Files
6971:
6972: sub save_selected_files {
6973: my ($user, $path, @files) = @_;
6974: my $filename = $user."savedfiles";
1.573 banghart 6975: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6976: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6977: foreach my $file (@files) {
1.620 albertel 6978: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6979: }
6980: foreach my $file (@other_files) {
1.574 banghart 6981: print (OUT $file."\n");
1.572 banghart 6982: }
1.574 banghart 6983: close (OUT);
1.572 banghart 6984: return 'ok';
6985: }
6986:
1.574 banghart 6987: sub clear_selected_files {
6988: my ($user) = @_;
6989: my $filename = $user."savedfiles";
6990: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6991: print (OUT undef);
6992: close (OUT);
6993: return ("ok");
6994: }
6995:
1.572 banghart 6996: sub files_in_path {
6997: my ($user, $path) = @_;
6998: my $filename = $user."savedfiles";
6999: my %return_files;
1.574 banghart 7000: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7001: while (my $line_in = <IN>) {
1.574 banghart 7002: chomp ($line_in);
7003: my @paths_and_file = split (m!/!, $line_in);
7004: my $file_part = pop (@paths_and_file);
7005: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7006: $path_part.='/';
7007: my $path_and_file = $path_part.$file_part;
7008: if ($path_part eq $path) {
7009: $return_files{$file_part}= 'selected';
7010: }
7011: }
1.574 banghart 7012: close (IN);
7013: return (\%return_files);
1.572 banghart 7014: }
7015:
7016: # called in portfolio select mode, to show files selected NOT in current directory
7017: sub files_not_in_path {
7018: my ($user, $path) = @_;
7019: my $filename = $user."savedfiles";
7020: my @return_files;
7021: my $path_part;
1.800 albertel 7022: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7023: while (my $line = <IN>) {
1.572 banghart 7024: #ok, I know it's clunky, but I want it to work
1.800 albertel 7025: my @paths_and_file = split(m|/|, $line);
7026: my $file_part = pop(@paths_and_file);
7027: chomp($file_part);
7028: my $path_part = join('/', @paths_and_file);
1.572 banghart 7029: $path_part .= '/';
7030: my $path_and_file = $path_part.$file_part;
7031: if ($path_part ne $path) {
1.800 albertel 7032: push(@return_files, ($path_and_file));
1.572 banghart 7033: }
7034: }
1.800 albertel 7035: close(OUT);
1.574 banghart 7036: return (@return_files);
1.572 banghart 7037: }
7038:
1.745 raeburn 7039: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7040:
1.745 raeburn 7041: sub get_portfile_permissions {
7042: my ($domain,$user) = @_;
1.613 albertel 7043: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7044: my ($tmp)=keys(%current_permissions);
7045: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7046: return \%current_permissions;
7047: }
7048:
7049: #---------------------------------------------Get portfolio file access controls
7050:
1.749 raeburn 7051: sub get_access_controls {
1.745 raeburn 7052: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7053: my %access;
7054: my $real_file = $file;
7055: $file =~ s/\.meta$//;
1.745 raeburn 7056: if (defined($file)) {
1.749 raeburn 7057: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7058: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7059: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7060: }
7061: }
1.745 raeburn 7062: } else {
1.749 raeburn 7063: foreach my $key (keys(%{$current_permissions})) {
7064: if ($key =~ /\0accesscontrol$/) {
7065: if (defined($group)) {
7066: if ($key !~ m-^\Q$group\E/-) {
7067: next;
7068: }
7069: }
7070: my ($fullpath) = split(/\0/,$key);
7071: if (ref($$current_permissions{$key}) eq 'HASH') {
7072: foreach my $control (keys(%{$$current_permissions{$key}})) {
7073: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7074: }
7075: }
7076: }
7077: }
7078: }
7079: return %access;
7080: }
7081:
7082: sub modify_access_controls {
7083: my ($file_name,$changes,$domain,$user)=@_;
7084: my ($outcome,$deloutcome);
7085: my %store_permissions;
7086: my %new_values;
7087: my %new_control;
7088: my %translation;
7089: my @deletions = ();
7090: my $now = time;
7091: if (exists($$changes{'activate'})) {
7092: if (ref($$changes{'activate'}) eq 'HASH') {
7093: my @newitems = sort(keys(%{$$changes{'activate'}}));
7094: my $numnew = scalar(@newitems);
7095: for (my $i=0; $i<$numnew; $i++) {
7096: my $newkey = $newitems[$i];
7097: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7098: if ($newkey =~ /^\d+:/) {
7099: $newkey =~ s/^(\d+)/$newid/;
7100: $translation{$1} = $newid;
7101: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7102: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7103: $translation{$1} = $newid;
7104: }
1.749 raeburn 7105: $new_values{$file_name."\0".$newkey} =
7106: $$changes{'activate'}{$newitems[$i]};
7107: $new_control{$newkey} = $now;
7108: }
7109: }
7110: }
7111: my %todelete;
7112: my %changed_items;
7113: foreach my $action ('delete','update') {
7114: if (exists($$changes{$action})) {
7115: if (ref($$changes{$action}) eq 'HASH') {
7116: foreach my $key (keys(%{$$changes{$action}})) {
7117: my ($itemnum) = ($key =~ /^([^:]+):/);
7118: if ($action eq 'delete') {
7119: $todelete{$itemnum} = 1;
7120: } else {
7121: $changed_items{$itemnum} = $key;
7122: }
7123: }
1.745 raeburn 7124: }
7125: }
1.749 raeburn 7126: }
7127: # get lock on access controls for file.
7128: my $lockhash = {
7129: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7130: ':'.$env{'user.domain'},
7131: };
7132: my $tries = 0;
7133: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7134:
7135: while (($gotlock ne 'ok') && $tries <3) {
7136: $tries ++;
7137: sleep 1;
7138: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7139: }
7140: if ($gotlock eq 'ok') {
7141: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7142: my ($tmp)=keys(%curr_permissions);
7143: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7144: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7145: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7146: if (ref($curr_controls) eq 'HASH') {
7147: foreach my $control_item (keys(%{$curr_controls})) {
7148: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7149: if (defined($todelete{$itemnum})) {
7150: push(@deletions,$file_name."\0".$control_item);
7151: } else {
7152: if (defined($changed_items{$itemnum})) {
7153: $new_control{$changed_items{$itemnum}} = $now;
7154: push(@deletions,$file_name."\0".$control_item);
7155: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7156: } else {
7157: $new_control{$control_item} = $$curr_controls{$control_item};
7158: }
7159: }
1.745 raeburn 7160: }
7161: }
7162: }
1.970 raeburn 7163: my ($group);
7164: if (&is_course($domain,$user)) {
7165: ($group,my $file) = split(/\//,$file_name,2);
7166: }
1.749 raeburn 7167: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7168: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7169: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7170: # remove lock
7171: my @del_lock = ($file_name."\0".'locked_access_records');
7172: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7173: my $sqlresult =
1.970 raeburn 7174: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7175: $group);
1.749 raeburn 7176: } else {
7177: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7178: }
1.749 raeburn 7179: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7180: }
7181:
1.827 raeburn 7182: sub make_public_indefinitely {
7183: my ($requrl) = @_;
7184: my $now = time;
7185: my $action = 'activate';
7186: my $aclnum = 0;
7187: if (&is_portfolio_url($requrl)) {
7188: my (undef,$udom,$unum,$file_name,$group) =
7189: &parse_portfolio_url($requrl);
7190: my $current_perms = &get_portfile_permissions($udom,$unum);
7191: my %access_controls = &get_access_controls($current_perms,
7192: $group,$file_name);
7193: foreach my $key (keys(%{$access_controls{$file_name}})) {
7194: my ($num,$scope,$end,$start) =
7195: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7196: if ($scope eq 'public') {
7197: if ($start <= $now && $end == 0) {
7198: $action = 'none';
7199: } else {
7200: $action = 'update';
7201: $aclnum = $num;
7202: }
7203: last;
7204: }
7205: }
7206: if ($action eq 'none') {
7207: return 'ok';
7208: } else {
7209: my %changes;
7210: my $newend = 0;
7211: my $newstart = $now;
7212: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7213: $changes{$action}{$newkey} = {
7214: type => 'public',
7215: time => {
7216: start => $newstart,
7217: end => $newend,
7218: },
7219: };
7220: my ($outcome,$deloutcome,$new_values,$translation) =
7221: &modify_access_controls($file_name,\%changes,$udom,$unum);
7222: return $outcome;
7223: }
7224: } else {
7225: return 'invalid';
7226: }
7227: }
7228:
1.745 raeburn 7229: #------------------------------------------------------Get Marked as Read Only
7230:
7231: sub get_marked_as_readonly {
7232: my ($domain,$user,$what,$group) = @_;
7233: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7234: my @readonly_files;
1.629 banghart 7235: my $cmp1=$what;
7236: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7237: while (my ($file_name,$value) = each(%{$current_permissions})) {
7238: if (defined($group)) {
7239: if ($file_name !~ m-^\Q$group\E/-) {
7240: next;
7241: }
7242: }
1.561 banghart 7243: if (ref($value) eq "ARRAY"){
7244: foreach my $stored_what (@{$value}) {
1.629 banghart 7245: my $cmp2=$stored_what;
1.759 albertel 7246: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7247: $cmp2=join('',@{$stored_what});
1.745 raeburn 7248: }
1.629 banghart 7249: if ($cmp1 eq $cmp2) {
1.561 banghart 7250: push(@readonly_files, $file_name);
1.745 raeburn 7251: last;
1.563 banghart 7252: } elsif (!defined($what)) {
7253: push(@readonly_files, $file_name);
1.745 raeburn 7254: last;
1.561 banghart 7255: }
7256: }
1.745 raeburn 7257: }
1.561 banghart 7258: }
7259: return @readonly_files;
7260: }
1.577 banghart 7261: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7262:
1.577 banghart 7263: sub get_marked_as_readonly_hash {
1.745 raeburn 7264: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7265: my %readonly_files;
1.745 raeburn 7266: while (my ($file_name,$value) = each(%{$current_permissions})) {
7267: if (defined($group)) {
7268: if ($file_name !~ m-^\Q$group\E/-) {
7269: next;
7270: }
7271: }
1.577 banghart 7272: if (ref($value) eq "ARRAY"){
7273: foreach my $stored_what (@{$value}) {
1.745 raeburn 7274: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7275: foreach my $lock_descriptor(@{$stored_what}) {
7276: if ($lock_descriptor eq 'graded') {
7277: $readonly_files{$file_name} = 'graded';
7278: } elsif ($lock_descriptor eq 'handback') {
7279: $readonly_files{$file_name} = 'handback';
7280: } else {
7281: if (!exists($readonly_files{$file_name})) {
7282: $readonly_files{$file_name} = 'locked';
7283: }
7284: }
1.745 raeburn 7285: }
1.750 banghart 7286: }
1.577 banghart 7287: }
7288: }
7289: }
7290: return %readonly_files;
7291: }
1.559 banghart 7292: # ------------------------------------------------------------ Unmark as Read Only
7293:
7294: sub unmark_as_readonly {
1.629 banghart 7295: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7296: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7297: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7298: $file_name = &declutter_portfile($file_name);
1.634 albertel 7299: my $symb_crs = $what;
7300: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7301: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7302: my ($tmp)=keys(%current_permissions);
7303: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7304: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7305: foreach my $file (@readonly_files) {
1.759 albertel 7306: my $clean_file = &declutter_portfile($file);
7307: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7308: my $current_locks = $current_permissions{$file};
1.563 banghart 7309: my @new_locks;
7310: my @del_keys;
7311: if (ref($current_locks) eq "ARRAY"){
7312: foreach my $locker (@{$current_locks}) {
1.632 albertel 7313: my $compare=$locker;
1.749 raeburn 7314: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7315: $compare=join('',@{$locker});
1.746 raeburn 7316: if ($compare ne $symb_crs) {
7317: push(@new_locks, $locker);
7318: }
1.563 banghart 7319: }
7320: }
1.650 albertel 7321: if (scalar(@new_locks) > 0) {
1.563 banghart 7322: $current_permissions{$file} = \@new_locks;
7323: } else {
7324: push(@del_keys, $file);
1.613 albertel 7325: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7326: delete($current_permissions{$file});
1.563 banghart 7327: }
7328: }
1.561 banghart 7329: }
1.613 albertel 7330: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7331: return;
7332: }
1.512 banghart 7333:
1.17 www 7334: # ------------------------------------------------------------ Directory lister
7335:
7336: sub dirlist {
1.955 raeburn 7337: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7338: $uri=~s/^\///;
7339: $uri=~s/\/$//;
1.253 stredwic 7340: my ($udom, $uname);
1.955 raeburn 7341: if ($getuserdir) {
1.253 stredwic 7342: $udom = $userdomain;
7343: $uname = $username;
1.955 raeburn 7344: } else {
7345: (undef,$udom,$uname)=split(/\//,$uri);
7346: if(defined($userdomain)) {
7347: $udom = $userdomain;
7348: }
7349: if(defined($username)) {
7350: $uname = $username;
7351: }
1.253 stredwic 7352: }
1.955 raeburn 7353: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7354:
1.955 raeburn 7355: $dirRoot = $perlvar{'lonDocRoot'};
7356: if (defined($getpropath)) {
7357: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7358: $dirRoot =~ s/\/$//;
1.955 raeburn 7359: } elsif (defined($getuserdir)) {
7360: my $subdir=$uname.'__';
7361: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7362: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7363: ."/$udom/$subdir/$uname";
7364: } elsif (defined($alternateRoot)) {
7365: $dirRoot = $alternateRoot;
1.751 banghart 7366: }
1.253 stredwic 7367:
7368: if($udom) {
7369: if($uname) {
1.955 raeburn 7370: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7371: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7372: .':'.&escape($uname).':'.&escape($udom),
7373: &homeserver($uname,$udom));
7374: if ($listing eq 'unknown_cmd') {
7375: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7376: &homeserver($uname,$udom));
7377: } else {
7378: @listing_results = map { &unescape($_); } split(/:/,$listing);
7379: }
1.605 matthew 7380: if ($listing eq 'unknown_cmd') {
1.800 albertel 7381: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7382: &homeserver($uname,$udom));
1.605 matthew 7383: @listing_results = split(/:/,$listing);
7384: } else {
7385: @listing_results = map { &unescape($_); } split(/:/,$listing);
7386: }
7387: return @listing_results;
1.955 raeburn 7388: } elsif(!$alternateRoot) {
1.800 albertel 7389: my %allusers;
1.841 albertel 7390: my %servers = &get_servers($udom,'library');
1.955 raeburn 7391: foreach my $tryserver (keys(%servers)) {
7392: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7393: &escape($udom),$tryserver);
7394: if ($listing eq 'unknown_cmd') {
7395: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7396: $udom, $tryserver);
7397: } else {
7398: @listing_results = map { &unescape($_); } split(/:/,$listing);
7399: }
1.841 albertel 7400: if ($listing eq 'unknown_cmd') {
7401: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7402: $udom, $tryserver);
7403: @listing_results = split(/:/,$listing);
7404: } else {
7405: @listing_results =
7406: map { &unescape($_); } split(/:/,$listing);
7407: }
7408: if ($listing_results[0] ne 'no_such_dir' &&
7409: $listing_results[0] ne 'empty' &&
7410: $listing_results[0] ne 'con_lost') {
7411: foreach my $line (@listing_results) {
7412: my ($entry) = split(/&/,$line,2);
7413: $allusers{$entry} = 1;
7414: }
7415: }
1.253 stredwic 7416: }
7417: my $alluserstr='';
1.800 albertel 7418: foreach my $user (sort(keys(%allusers))) {
7419: $alluserstr.=$user.'&user:';
1.253 stredwic 7420: }
7421: $alluserstr=~s/:$//;
7422: return split(/:/,$alluserstr);
7423: } else {
1.800 albertel 7424: return ('missing user name');
1.253 stredwic 7425: }
1.955 raeburn 7426: } elsif(!defined($getpropath)) {
1.841 albertel 7427: my @all_domains = sort(&all_domains());
1.955 raeburn 7428: foreach my $domain (@all_domains) {
7429: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7430: }
7431: return @all_domains;
7432: } else {
1.800 albertel 7433: return ('missing domain');
1.275 stredwic 7434: }
7435: }
7436:
7437: # --------------------------------------------- GetFileTimestamp
7438: # This function utilizes dirlist and returns the date stamp for
7439: # when it was last modified. It will also return an error of -1
7440: # if an error occurs
7441:
7442: sub GetFileTimestamp {
1.955 raeburn 7443: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7444: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7445: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7446: my ($fileStat) =
7447: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7448: undef,$getuserdir);
1.275 stredwic 7449: my @stats = split('&', $fileStat);
7450: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7451: # @stats contains first the filename, then the stat output
7452: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7453: } else {
7454: return -1;
1.253 stredwic 7455: }
1.26 www 7456: }
7457:
1.712 albertel 7458: sub stat_file {
7459: my ($uri) = @_;
1.787 albertel 7460: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7461:
1.955 raeburn 7462: my ($udom,$uname,$file);
1.712 albertel 7463: if ($uri =~ m-^/(uploaded|editupload)/-) {
7464: ($udom,$uname,$file) =
1.811 albertel 7465: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7466: $file = 'userfiles/'.$file;
7467: }
7468: if ($uri =~ m-^/res/-) {
7469: ($udom,$uname) =
1.807 albertel 7470: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7471: $file = $uri;
7472: }
7473:
7474: if (!$udom || !$uname || !$file) {
7475: # unable to handle the uri
7476: return ();
7477: }
1.956 raeburn 7478: my $getpropath;
7479: if ($file =~ /^userfiles\//) {
7480: $getpropath = 1;
7481: }
1.955 raeburn 7482: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7483: my @stats = split('&', $result);
1.721 banghart 7484:
1.712 albertel 7485: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7486: shift(@stats); #filename is first
7487: return @stats;
7488: }
7489: return ();
7490: }
7491:
1.26 www 7492: # -------------------------------------------------------- Value of a Condition
7493:
1.713 albertel 7494: # gets the value of a specific preevaluated condition
7495: # stored in the string $env{user.state.<cid>}
7496: # or looks up a condition reference in the bighash and if if hasn't
7497: # already been evaluated recurses into docondval to get the value of
7498: # the condition, then memoizing it to
7499: # $env{user.state.<cid>.<condition>}
1.40 www 7500: sub directcondval {
7501: my $number=shift;
1.620 albertel 7502: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7503: &Apache::lonuserstate::evalstate();
7504: }
1.713 albertel 7505: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7506: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7507: } elsif ($number =~ /^_/) {
7508: my $sub_condition;
7509: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7510: &GDBM_READER(),0640)) {
7511: $sub_condition=$bighash{'conditions'.$number};
7512: untie(%bighash);
7513: }
7514: my $value = &docondval($sub_condition);
1.949 raeburn 7515: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7516: return $value;
7517: }
1.620 albertel 7518: if ($env{'user.state.'.$env{'request.course.id'}}) {
7519: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7520: } else {
7521: return 2;
7522: }
7523: }
7524:
1.713 albertel 7525: # get the collection of conditions for this resource
1.26 www 7526: sub condval {
7527: my $condidx=shift;
1.54 www 7528: my $allpathcond='';
1.713 albertel 7529: foreach my $cond (split(/\|/,$condidx)) {
7530: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7531: $allpathcond.=
7532: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7533: }
1.191 harris41 7534: }
1.54 www 7535: $allpathcond=~s/\|$//;
1.713 albertel 7536: return &docondval($allpathcond);
7537: }
7538:
7539: #evaluates an expression of conditions
7540: sub docondval {
7541: my ($allpathcond) = @_;
7542: my $result=0;
7543: if ($env{'request.course.id'}
7544: && defined($allpathcond)) {
7545: my $operand='|';
7546: my @stack;
7547: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7548: if ($chunk eq '(') {
7549: push @stack,($operand,$result);
7550: } elsif ($chunk eq ')') {
7551: my $before=pop @stack;
7552: if (pop @stack eq '&') {
7553: $result=$result>$before?$before:$result;
7554: } else {
7555: $result=$result>$before?$result:$before;
7556: }
7557: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7558: $operand=$chunk;
7559: } else {
7560: my $new=directcondval($chunk);
7561: if ($operand eq '&') {
7562: $result=$result>$new?$new:$result;
7563: } else {
7564: $result=$result>$new?$result:$new;
7565: }
7566: }
7567: }
1.26 www 7568: }
7569: return $result;
1.421 albertel 7570: }
7571:
7572: # ---------------------------------------------------- Devalidate courseresdata
7573:
7574: sub devalidatecourseresdata {
7575: my ($coursenum,$coursedomain)=@_;
7576: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7577: &devalidate_cache_new('courseres',$hashid);
1.28 www 7578: }
7579:
1.763 www 7580:
1.200 www 7581: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7582: #
7583: # Parameters:
7584: # $coursenum - Number of the course.
7585: # $coursedomain - Domain at which the course was created.
7586: # Returns:
7587: # A hash of the course parameters along (I think) with timestamps
7588: # and version info.
1.877 foxr 7589:
1.624 albertel 7590: sub get_courseresdata {
7591: my ($coursenum,$coursedomain)=@_;
1.200 www 7592: my $coursehom=&homeserver($coursenum,$coursedomain);
7593: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7594: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7595: my %dumpreply;
1.417 albertel 7596: unless (defined($cached)) {
1.624 albertel 7597: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7598: $result=\%dumpreply;
1.251 albertel 7599: my ($tmp) = keys(%dumpreply);
7600: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7601: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7602: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7603: return $tmp;
1.416 albertel 7604: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7605: $result=undef;
1.599 albertel 7606: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7607: }
7608: }
1.624 albertel 7609: return $result;
7610: }
7611:
1.633 albertel 7612: sub devalidateuserresdata {
7613: my ($uname,$udom)=@_;
7614: my $hashid="$udom:$uname";
7615: &devalidate_cache_new('userres',$hashid);
7616: }
7617:
1.624 albertel 7618: sub get_userresdata {
7619: my ($uname,$udom)=@_;
7620: #most student don\'t have any data set, check if there is some data
7621: if (&EXT_cache_status($udom,$uname)) { return undef; }
7622:
7623: my $hashid="$udom:$uname";
7624: my ($result,$cached)=&is_cached_new('userres',$hashid);
7625: if (!defined($cached)) {
7626: my %resourcedata=&dump('resourcedata',$udom,$uname);
7627: $result=\%resourcedata;
7628: &do_cache_new('userres',$hashid,$result,600);
7629: }
7630: my ($tmp)=keys(%$result);
7631: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7632: return $result;
7633: }
7634: #error 2 occurs when the .db doesn't exist
7635: if ($tmp!~/error: 2 /) {
1.672 albertel 7636: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7637: " Trying to get resource data for ".
7638: $uname." at ".$udom.": ".
7639: $tmp."</font>");
7640: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7641: #&EXT_cache_set($udom,$uname);
7642: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7643: undef($tmp); # not really an error so don't send it back
1.624 albertel 7644: }
7645: return $tmp;
7646: }
1.879 foxr 7647: #----------------------------------------------- resdata - return resource data
7648: # Purpose:
7649: # Return resource data for either users or for a course.
7650: # Parameters:
7651: # $name - Course/user name.
7652: # $domain - Name of the domain the user/course is registered on.
7653: # $type - Type of thing $name is (must be 'course' or 'user'
7654: # @which - Array of names of resources desired.
7655: # Returns:
7656: # The value of the first reasource in @which that is found in the
7657: # resource hash.
7658: # Exceptional Conditions:
7659: # If the $type passed in is not valid (not the string 'course' or
7660: # 'user', an undefined reference is returned.
7661: # If none of the resources are found, an undef is returned
1.624 albertel 7662: sub resdata {
7663: my ($name,$domain,$type,@which)=@_;
7664: my $result;
7665: if ($type eq 'course') {
7666: $result=&get_courseresdata($name,$domain);
7667: } elsif ($type eq 'user') {
7668: $result=&get_userresdata($name,$domain);
7669: }
7670: if (!ref($result)) { return $result; }
1.251 albertel 7671: foreach my $item (@which) {
1.927 albertel 7672: if (defined($result->{$item->[0]})) {
7673: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7674: }
1.250 albertel 7675: }
1.291 albertel 7676: return undef;
1.200 www 7677: }
7678:
1.379 matthew 7679: #
7680: # EXT resource caching routines
7681: #
7682:
7683: sub clear_EXT_cache_status {
1.383 albertel 7684: &delenv('cache.EXT.');
1.379 matthew 7685: }
7686:
7687: sub EXT_cache_status {
7688: my ($target_domain,$target_user) = @_;
1.383 albertel 7689: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7690: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7691: # We know already the user has no data
7692: return 1;
7693: } else {
7694: return 0;
7695: }
7696: }
7697:
7698: sub EXT_cache_set {
7699: my ($target_domain,$target_user) = @_;
1.383 albertel 7700: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7701: #&appenv({$cachename => time});
1.379 matthew 7702: }
7703:
1.28 www 7704: # --------------------------------------------------------- Value of a Variable
1.58 www 7705: sub EXT {
1.715 albertel 7706:
1.395 albertel 7707: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7708: unless ($varname) { return ''; }
1.218 albertel 7709: #get real user name/domain, courseid and symb
7710: my $courseid;
1.359 albertel 7711: my $publicuser;
1.427 www 7712: if ($symbparm) {
7713: $symbparm=&get_symb_from_alias($symbparm);
7714: }
1.218 albertel 7715: if (!($uname && $udom)) {
1.790 albertel 7716: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7717: if (!$symbparm) { $symbparm=$cursymb; }
7718: } else {
1.620 albertel 7719: $courseid=$env{'request.course.id'};
1.218 albertel 7720: }
1.48 www 7721: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7722: my $rest;
1.320 albertel 7723: if (defined($therest[0])) {
1.48 www 7724: $rest=join('.',@therest);
7725: } else {
7726: $rest='';
7727: }
1.320 albertel 7728:
1.57 www 7729: my $qualifierrest=$qualifier;
7730: if ($rest) { $qualifierrest.='.'.$rest; }
7731: my $spacequalifierrest=$space;
7732: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7733: if ($realm eq 'user') {
1.48 www 7734: # --------------------------------------------------------------- user.resource
7735: if ($space eq 'resource') {
1.651 albertel 7736: if ( (defined($Apache::lonhomework::parsing_a_problem)
7737: || defined($Apache::lonhomework::parsing_a_task))
7738: &&
1.744 albertel 7739: ($symbparm eq &symbread()) ) {
7740: # if we are in the middle of processing the resource the
7741: # get the value we are planning on committing
7742: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7743: return $Apache::lonhomework::results{$qualifierrest};
7744: } else {
7745: return $Apache::lonhomework::history{$qualifierrest};
7746: }
1.335 albertel 7747: } else {
1.359 albertel 7748: my %restored;
1.620 albertel 7749: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7750: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7751: } else {
7752: %restored=&restore($symbparm,$courseid,$udom,$uname);
7753: }
1.335 albertel 7754: return $restored{$qualifierrest};
7755: }
1.48 www 7756: # ----------------------------------------------------------------- user.access
7757: } elsif ($space eq 'access') {
1.218 albertel 7758: # FIXME - not supporting calls for a specific user
1.48 www 7759: return &allowed($qualifier,$rest);
7760: # ------------------------------------------ user.preferences, user.environment
7761: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7762: if (($uname eq $env{'user.name'}) &&
7763: ($udom eq $env{'user.domain'})) {
7764: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7765: } else {
1.359 albertel 7766: my %returnhash;
7767: if (!$publicuser) {
7768: %returnhash=&userenvironment($udom,$uname,
7769: $qualifierrest);
7770: }
1.218 albertel 7771: return $returnhash{$qualifierrest};
7772: }
1.48 www 7773: # ----------------------------------------------------------------- user.course
7774: } elsif ($space eq 'course') {
1.218 albertel 7775: # FIXME - not supporting calls for a specific user
1.620 albertel 7776: return $env{join('.',('request.course',$qualifier))};
1.48 www 7777: # ------------------------------------------------------------------- user.role
7778: } elsif ($space eq 'role') {
1.218 albertel 7779: # FIXME - not supporting calls for a specific user
1.620 albertel 7780: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7781: if ($qualifier eq 'value') {
7782: return $role;
7783: } elsif ($qualifier eq 'extent') {
7784: return $where;
7785: }
7786: # ----------------------------------------------------------------- user.domain
7787: } elsif ($space eq 'domain') {
1.218 albertel 7788: return $udom;
1.48 www 7789: # ------------------------------------------------------------------- user.name
7790: } elsif ($space eq 'name') {
1.218 albertel 7791: return $uname;
1.48 www 7792: # ---------------------------------------------------- Any other user namespace
1.29 www 7793: } else {
1.359 albertel 7794: my %reply;
7795: if (!$publicuser) {
7796: %reply=&get($space,[$qualifierrest],$udom,$uname);
7797: }
7798: return $reply{$qualifierrest};
1.48 www 7799: }
1.236 www 7800: } elsif ($realm eq 'query') {
7801: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7802: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7803: [$spacequalifierrest]);
1.620 albertel 7804: return $env{'form.'.$spacequalifierrest};
1.236 www 7805: } elsif ($realm eq 'request') {
1.48 www 7806: # ------------------------------------------------------------- request.browser
7807: if ($space eq 'browser') {
1.430 www 7808: if ($qualifier eq 'textremote') {
1.676 albertel 7809: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7810: return 1;
7811: } else {
7812: return 0;
7813: }
7814: } else {
1.620 albertel 7815: return $env{'browser.'.$qualifier};
1.430 www 7816: }
1.57 www 7817: # ------------------------------------------------------------ request.filename
7818: } else {
1.620 albertel 7819: return $env{'request.'.$spacequalifierrest};
1.29 www 7820: }
1.28 www 7821: } elsif ($realm eq 'course') {
1.48 www 7822: # ---------------------------------------------------------- course.description
1.620 albertel 7823: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7824: } elsif ($realm eq 'resource') {
1.165 www 7825:
1.620 albertel 7826: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7827: if (!$symbparm) { $symbparm=&symbread(); }
7828: }
1.693 albertel 7829:
7830: if ($space eq 'title') {
7831: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7832: return &gettitle($symbparm);
7833: }
7834:
7835: if ($space eq 'map') {
7836: my ($map) = &decode_symb($symbparm);
7837: return &symbread($map);
7838: }
1.905 albertel 7839: if ($space eq 'filename') {
7840: if ($symbparm) {
7841: return &clutter((&decode_symb($symbparm))[2]);
7842: }
7843: return &hreflocation('',$env{'request.filename'});
7844: }
1.693 albertel 7845:
7846: my ($section, $group, @groups);
1.593 albertel 7847: my ($courselevelm,$courselevel);
1.539 albertel 7848: if ($symbparm && defined($courseid) &&
1.620 albertel 7849: $courseid eq $env{'request.course.id'}) {
1.165 www 7850:
1.218 albertel 7851: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7852:
1.60 www 7853: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7854: my $symbp=$symbparm;
1.735 albertel 7855: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7856:
7857: my $symbparm=$symbp.'.'.$spacequalifierrest;
7858: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7859:
1.620 albertel 7860: if (($env{'user.name'} eq $uname) &&
7861: ($env{'user.domain'} eq $udom)) {
7862: $section=$env{'request.course.sec'};
1.733 raeburn 7863: @groups = split(/:/,$env{'request.course.groups'});
7864: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7865: } else {
1.539 albertel 7866: if (! defined($usection)) {
1.551 albertel 7867: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7868: } else {
7869: $section = $usection;
7870: }
1.733 raeburn 7871: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7872: }
7873:
7874: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7875: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7876: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7877:
1.593 albertel 7878: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7879: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7880: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7881:
1.60 www 7882: # ----------------------------------------------------------- first, check user
1.624 albertel 7883:
7884: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7885: ([$courselevelr,'resource'],
7886: [$courselevelm,'map' ],
7887: [$courselevel, 'course' ]));
1.931 albertel 7888: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7889:
1.594 albertel 7890: # ------------------------------------------------ second, check some of course
1.684 raeburn 7891: my $coursereply;
1.691 raeburn 7892: if (@groups > 0) {
7893: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7894: $mapparm,$spacequalifierrest);
1.927 albertel 7895: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7896: }
1.96 www 7897:
1.684 raeburn 7898: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7899: $env{'course.'.$courseid.'.domain'},
7900: 'course',
7901: ([$seclevelr, 'resource'],
7902: [$seclevelm, 'map' ],
7903: [$seclevel, 'course' ],
7904: [$courselevelr,'resource']));
7905: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7906:
1.60 www 7907: # ------------------------------------------------------ third, check map parms
1.218 albertel 7908: my %parmhash=();
7909: my $thisparm='';
7910: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7911: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7912: &GDBM_READER(),0640)) {
1.218 albertel 7913: $thisparm=$parmhash{$symbparm};
7914: untie(%parmhash);
7915: }
1.927 albertel 7916: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7917: }
1.594 albertel 7918: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7919:
1.218 albertel 7920: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7921: my $filename;
7922: if (!$symbparm) { $symbparm=&symbread(); }
7923: if ($symbparm) {
1.409 www 7924: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7925: } else {
1.620 albertel 7926: $filename=$env{'request.filename'};
1.282 albertel 7927: }
7928: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7929: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7930: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7931: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7932:
1.927 albertel 7933: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7934: if ($symbparm && defined($courseid) &&
1.620 albertel 7935: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7936: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7937: $env{'course.'.$courseid.'.domain'},
7938: 'course',
1.927 albertel 7939: ([$courselevelm,'map' ],
7940: [$courselevel, 'course']));
7941: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7942: }
1.145 www 7943: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7944: unless ($space eq '0') {
1.336 albertel 7945: my @parts=split(/_/,$space);
7946: my $id=pop(@parts);
7947: my $part=join('_',@parts);
7948: if ($part eq '') { $part='0'; }
1.927 albertel 7949: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7950: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7951: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7952: }
1.395 albertel 7953: if ($recurse) { return undef; }
7954: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7955: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7956: # ---------------------------------------------------- Any other user namespace
7957: } elsif ($realm eq 'environment') {
7958: # ----------------------------------------------------------------- environment
1.620 albertel 7959: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7960: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7961: } else {
1.770 albertel 7962: if ($uname eq 'anonymous' && $udom eq '') {
7963: return '';
7964: }
1.219 albertel 7965: my %returnhash=&userenvironment($udom,$uname,
7966: $spacequalifierrest);
7967: return $returnhash{$spacequalifierrest};
7968: }
1.28 www 7969: } elsif ($realm eq 'system') {
1.48 www 7970: # ----------------------------------------------------------------- system.time
7971: if ($space eq 'time') {
7972: return time;
7973: }
1.696 albertel 7974: } elsif ($realm eq 'server') {
7975: # ----------------------------------------------------------------- system.time
7976: if ($space eq 'name') {
7977: return $ENV{'SERVER_NAME'};
7978: }
1.28 www 7979: }
1.48 www 7980: return '';
1.61 www 7981: }
7982:
1.927 albertel 7983: sub get_reply {
7984: my ($reply_value) = @_;
1.940 raeburn 7985: if (ref($reply_value) eq 'ARRAY') {
7986: if (wantarray) {
7987: return @$reply_value;
7988: }
7989: return $reply_value->[0];
7990: } else {
7991: return $reply_value;
1.927 albertel 7992: }
7993: }
7994:
1.691 raeburn 7995: sub check_group_parms {
7996: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7997: my @groupitems = ();
7998: my $resultitem;
1.927 albertel 7999: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8000: foreach my $group (@{$groups}) {
8001: foreach my $level (@levels) {
1.927 albertel 8002: my $item = $courseid.'.['.$group.'].'.$level->[0];
8003: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8004: }
8005: }
8006: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8007: $env{'course.'.$courseid.'.domain'},
8008: 'course',@groupitems);
8009: return $coursereply;
8010: }
8011:
8012: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8013: my ($courseid,@groups) = @_;
8014: @groups = sort(@groups);
1.691 raeburn 8015: return @groups;
8016: }
8017:
1.395 albertel 8018: sub packages_tab_default {
8019: my ($uri,$varname)=@_;
8020: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8021:
8022: my (@extension,@specifics,$do_default);
8023: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8024: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8025: if ($pack_type eq 'default') {
8026: $do_default=1;
8027: } elsif ($pack_type eq 'extension') {
8028: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8029: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8030: # only look at packages defaults for packages that this id is
1.738 albertel 8031: push(@specifics,[$package,$pack_type,$pack_part]);
8032: }
8033: }
8034: # first look for a package that matches the requested part id
8035: foreach my $package (@specifics) {
8036: my (undef,$pack_type,$pack_part)=@{$package};
8037: next if ($pack_part ne $part);
8038: if (defined($packagetab{"$pack_type&$name&default"})) {
8039: return $packagetab{"$pack_type&$name&default"};
8040: }
8041: }
8042: # look for any possible matching non extension_ package
8043: foreach my $package (@specifics) {
8044: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8045: if (defined($packagetab{"$pack_type&$name&default"})) {
8046: return $packagetab{"$pack_type&$name&default"};
8047: }
1.585 albertel 8048: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8049: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8050: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8051: }
8052: }
1.738 albertel 8053: # look for any posible extension_ match
8054: foreach my $package (@extension) {
8055: my ($package,$pack_type)=@{$package};
8056: if (defined($packagetab{"$pack_type&$name&default"})) {
8057: return $packagetab{"$pack_type&$name&default"};
8058: }
8059: if (defined($packagetab{$package."&$name&default"})) {
8060: return $packagetab{$package."&$name&default"};
8061: }
8062: }
8063: # look for a global default setting
8064: if ($do_default && defined($packagetab{"default&$name&default"})) {
8065: return $packagetab{"default&$name&default"};
8066: }
1.395 albertel 8067: return undef;
8068: }
8069:
1.334 albertel 8070: sub add_prefix_and_part {
8071: my ($prefix,$part)=@_;
8072: my $keyroot;
8073: if (defined($prefix) && $prefix !~ /^__/) {
8074: # prefix that has a part already
8075: $keyroot=$prefix;
8076: } elsif (defined($prefix)) {
8077: # prefix that is missing a part
8078: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8079: } else {
8080: # no prefix at all
8081: if (defined($part)) { $keyroot='_'.$part; }
8082: }
8083: return $keyroot;
8084: }
8085:
1.71 www 8086: # ---------------------------------------------------------------- Get metadata
8087:
1.599 albertel 8088: my %metaentry;
1.71 www 8089: sub metadata {
1.176 www 8090: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8091: $uri=&declutter($uri);
1.288 albertel 8092: # if it is a non metadata possible uri return quickly
1.529 albertel 8093: if (($uri eq '') ||
8094: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8095: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8096: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8097: return undef;
8098: }
8099: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8100: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8101: return undef;
1.288 albertel 8102: }
1.73 www 8103: my $filename=$uri;
8104: $uri=~s/\.meta$//;
1.172 www 8105: #
8106: # Is the metadata already cached?
1.177 www 8107: # Look at timestamp of caching
1.172 www 8108: # Everything is cached by the main uri, libraries are never directly cached
8109: #
1.428 albertel 8110: if (!defined($liburi)) {
1.599 albertel 8111: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8112: if (defined($cached)) { return $result->{':'.$what}; }
8113: }
8114: {
1.172 www 8115: #
8116: # Is this a recursive call for a library?
8117: #
1.599 albertel 8118: # if (! exists($metacache{$uri})) {
8119: # $metacache{$uri}={};
8120: # }
1.924 albertel 8121: my $cachetime = 60*60;
1.171 www 8122: if ($liburi) {
8123: $liburi=&declutter($liburi);
8124: $filename=$liburi;
1.401 bowersj2 8125: } else {
1.599 albertel 8126: &devalidate_cache_new('meta',$uri);
8127: undef(%metaentry);
1.401 bowersj2 8128: }
1.140 www 8129: my %metathesekeys=();
1.73 www 8130: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8131: my $metastring;
1.924 albertel 8132: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8133: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8134: $metastring =
1.929 albertel 8135: &Apache::lonnet::ssi_body($which,
1.924 albertel 8136: ('grade_target' => 'meta'));
8137: $cachetime = 1; # only want this cached in the child not long term
8138: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8139: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8140: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8141: $metastring=&getfile($file);
1.489 albertel 8142: }
1.208 albertel 8143: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8144: my $token;
1.140 www 8145: undef %metathesekeys;
1.71 www 8146: while ($token=$parser->get_token) {
1.339 albertel 8147: if ($token->[0] eq 'S') {
8148: if (defined($token->[2]->{'package'})) {
1.172 www 8149: #
8150: # This is a package - get package info
8151: #
1.339 albertel 8152: my $package=$token->[2]->{'package'};
8153: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8154: if (defined($token->[2]->{'id'})) {
8155: $keyroot.='_'.$token->[2]->{'id'};
8156: }
1.599 albertel 8157: if ($metaentry{':packages'}) {
8158: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8159: } else {
1.599 albertel 8160: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8161: }
1.736 albertel 8162: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8163: my $part=$keyroot;
8164: $part=~s/^\_//;
1.736 albertel 8165: if ($pack_entry=~/^\Q$package\E\&/ ||
8166: $pack_entry=~/^\Q$package\E_0\&/) {
8167: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8168: # ignore package.tab specified default values
8169: # here &package_tab_default() will fetch those
8170: if ($subp eq 'default') { next; }
1.736 albertel 8171: my $value=$packagetab{$pack_entry};
1.432 albertel 8172: my $unikey;
8173: if ($pack =~ /_0$/) {
8174: $unikey='parameter_0_'.$name;
8175: $part=0;
8176: } else {
8177: $unikey='parameter'.$keyroot.'_'.$name;
8178: }
1.339 albertel 8179: if ($subp eq 'display') {
8180: $value.=' [Part: '.$part.']';
8181: }
1.599 albertel 8182: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8183: $metathesekeys{$unikey}=1;
1.599 albertel 8184: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8185: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8186: }
1.599 albertel 8187: if (defined($metaentry{':'.$unikey.'.default'})) {
8188: $metaentry{':'.$unikey}=
8189: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8190: }
1.339 albertel 8191: }
8192: }
8193: } else {
1.172 www 8194: #
8195: # This is not a package - some other kind of start tag
1.339 albertel 8196: #
8197: my $entry=$token->[1];
8198: my $unikey;
8199: if ($entry eq 'import') {
8200: $unikey='';
8201: } else {
8202: $unikey=$entry;
8203: }
8204: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8205:
8206: if (defined($token->[2]->{'id'})) {
8207: $unikey.='_'.$token->[2]->{'id'};
8208: }
1.175 www 8209:
1.339 albertel 8210: if ($entry eq 'import') {
1.175 www 8211: #
8212: # Importing a library here
1.339 albertel 8213: #
8214: if ($depthcount<20) {
8215: my $location=$parser->get_text('/import');
8216: my $dir=$filename;
8217: $dir=~s|[^/]*$||;
8218: $location=&filelocation($dir,$location);
1.736 albertel 8219: my $metadata =
8220: &metadata($uri,'keys', $location,$unikey,
8221: $depthcount+1);
8222: foreach my $meta (split(',',$metadata)) {
8223: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8224: $metathesekeys{$meta}=1;
1.339 albertel 8225: }
8226: }
8227: } else {
8228:
8229: if (defined($token->[2]->{'name'})) {
8230: $unikey.='_'.$token->[2]->{'name'};
8231: }
8232: $metathesekeys{$unikey}=1;
1.736 albertel 8233: foreach my $param (@{$token->[3]}) {
8234: $metaentry{':'.$unikey.'.'.$param} =
8235: $token->[2]->{$param};
1.339 albertel 8236: }
8237: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8238: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8239: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8240: # only ws inside the tag, and not in default, so use default
8241: # as value
1.599 albertel 8242: $metaentry{':'.$unikey}=$default;
1.908 albertel 8243: } elsif ( $internaltext =~ /\S/ ) {
8244: # something interesting inside the tag
8245: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8246: } else {
1.908 albertel 8247: # no interesting values, don't set a default
1.339 albertel 8248: }
1.172 www 8249: # end of not-a-package not-a-library import
1.339 albertel 8250: }
1.172 www 8251: # end of not-a-package start tag
1.339 albertel 8252: }
1.172 www 8253: # the next is the end of "start tag"
1.339 albertel 8254: }
8255: }
1.483 albertel 8256: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8257: $extension = lc($extension);
8258: if ($extension eq 'htm') { $extension='html'; }
8259:
1.737 albertel 8260: foreach my $key (keys(%packagetab)) {
1.483 albertel 8261: #no specific packages #how's our extension
8262: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8263: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8264: \%metathesekeys);
8265: }
1.883 albertel 8266:
8267: if (!exists($metaentry{':packages'})
8268: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8269: foreach my $key (keys(%packagetab)) {
1.483 albertel 8270: #no specific packages well let's get default then
8271: if ($key!~/^default&/) { next; }
1.488 albertel 8272: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8273: \%metathesekeys);
8274: }
8275: }
1.338 www 8276: # are there custom rights to evaluate
1.599 albertel 8277: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8278:
1.338 www 8279: #
8280: # Importing a rights file here
1.339 albertel 8281: #
8282: unless ($depthcount) {
1.599 albertel 8283: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8284: my $dir=$filename;
8285: $dir=~s|[^/]*$||;
8286: $location=&filelocation($dir,$location);
1.736 albertel 8287: my $rights_metadata =
8288: &metadata($uri,'keys',$location,'_rights',
8289: $depthcount+1);
8290: foreach my $rights (split(',',$rights_metadata)) {
8291: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8292: $metathesekeys{$rights}=1;
1.339 albertel 8293: }
8294: }
8295: }
1.737 albertel 8296: # uniqifiy package listing
8297: my %seen;
8298: my @uniq_packages =
8299: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8300: $metaentry{':packages'} = join(',',@uniq_packages);
8301:
8302: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8303: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8304: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8305: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8306: # this is the end of "was not already recently cached
1.71 www 8307: }
1.599 albertel 8308: return $metaentry{':'.$what};
1.261 albertel 8309: }
8310:
1.488 albertel 8311: sub metadata_create_package_def {
1.483 albertel 8312: my ($uri,$key,$package,$metathesekeys)=@_;
8313: my ($pack,$name,$subp)=split(/\&/,$key);
8314: if ($subp eq 'default') { next; }
8315:
1.599 albertel 8316: if (defined($metaentry{':packages'})) {
8317: $metaentry{':packages'}.=','.$package;
1.483 albertel 8318: } else {
1.599 albertel 8319: $metaentry{':packages'}=$package;
1.483 albertel 8320: }
8321: my $value=$packagetab{$key};
8322: my $unikey;
8323: $unikey='parameter_0_'.$name;
1.599 albertel 8324: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8325: $$metathesekeys{$unikey}=1;
1.599 albertel 8326: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8327: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8328: }
1.599 albertel 8329: if (defined($metaentry{':'.$unikey.'.default'})) {
8330: $metaentry{':'.$unikey}=
8331: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8332: }
8333: }
8334:
1.261 albertel 8335: sub metadata_generate_part0 {
8336: my ($metadata,$metacache,$uri) = @_;
8337: my %allnames;
1.737 albertel 8338: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8339: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8340: my $part=$$metacache{':'.$metakey.'.part'};
8341: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8342: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8343: $allnames{$name}=$part;
8344: }
8345: }
8346: }
8347: foreach my $name (keys(%allnames)) {
8348: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8349: my $key=":parameter_0_$name";
1.261 albertel 8350: $$metacache{"$key.part"}='0';
8351: $$metacache{"$key.name"}=$name;
1.428 albertel 8352: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8353: $allnames{$name}.'_'.$name.
8354: '.type'};
1.428 albertel 8355: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8356: '.display'};
1.644 www 8357: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8358: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8359: $$metacache{"$key.display"}=$olddis;
8360: }
1.71 www 8361: }
8362:
1.764 albertel 8363: # ------------------------------------------------------ Devalidate title cache
8364:
8365: sub devalidate_title_cache {
8366: my ($url)=@_;
8367: if (!$env{'request.course.id'}) { return; }
8368: my $symb=&symbread($url);
8369: if (!$symb) { return; }
8370: my $key=$env{'request.course.id'}."\0".$symb;
8371: &devalidate_cache_new('title',$key);
8372: }
8373:
1.1014 droeschl 8374: # ------------------------------------------------- Get the title of a course
8375:
8376: sub current_course_title {
8377: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8378: }
1.301 www 8379: # ------------------------------------------------- Get the title of a resource
8380:
8381: sub gettitle {
8382: my $urlsymb=shift;
8383: my $symb=&symbread($urlsymb);
1.534 albertel 8384: if ($symb) {
1.620 albertel 8385: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8386: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8387: if (defined($cached)) {
8388: return $result;
8389: }
1.534 albertel 8390: my ($map,$resid,$url)=&decode_symb($symb);
8391: my $title='';
1.907 albertel 8392: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8393: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8394: } else {
8395: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8396: &GDBM_READER(),0640)) {
8397: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8398: $title=$bighash{'title_'.$mapid.'.'.$resid};
8399: untie(%bighash);
8400: }
1.534 albertel 8401: }
8402: $title=~s/\&colon\;/\:/gs;
8403: if ($title) {
1.599 albertel 8404: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8405: }
8406: $urlsymb=$url;
8407: }
8408: my $title=&metadata($urlsymb,'title');
8409: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8410: return $title;
1.301 www 8411: }
1.613 albertel 8412:
1.614 albertel 8413: sub get_slot {
8414: my ($which,$cnum,$cdom)=@_;
8415: if (!$cnum || !$cdom) {
1.790 albertel 8416: (undef,my $courseid)=&whichuser();
1.620 albertel 8417: $cdom=$env{'course.'.$courseid.'.domain'};
8418: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8419: }
1.703 albertel 8420: my $key=join("\0",'slots',$cdom,$cnum,$which);
8421: my %slotinfo;
8422: if (exists($remembered{$key})) {
8423: $slotinfo{$which} = $remembered{$key};
8424: } else {
8425: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8426: &Apache::lonhomework::showhash(%slotinfo);
8427: my ($tmp)=keys(%slotinfo);
8428: if ($tmp=~/^error:/) { return (); }
8429: $remembered{$key} = $slotinfo{$which};
8430: }
1.616 albertel 8431: if (ref($slotinfo{$which}) eq 'HASH') {
8432: return %{$slotinfo{$which}};
8433: }
8434: return $slotinfo{$which};
1.614 albertel 8435: }
1.31 www 8436: # ------------------------------------------------- Update symbolic store links
8437:
8438: sub symblist {
8439: my ($mapname,%newhash)=@_;
1.438 www 8440: $mapname=&deversion(&declutter($mapname));
1.31 www 8441: my %hash;
1.620 albertel 8442: if (($env{'request.course.fn'}) && (%newhash)) {
8443: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8444: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8445: foreach my $url (keys(%newhash)) {
1.711 albertel 8446: next if ($url eq 'last_known'
8447: && $env{'form.no_update_last_known'});
8448: $hash{declutter($url)}=&encode_symb($mapname,
8449: $newhash{$url}->[1],
8450: $newhash{$url}->[0]);
1.191 harris41 8451: }
1.31 www 8452: if (untie(%hash)) {
8453: return 'ok';
8454: }
8455: }
8456: }
8457: return 'error';
1.212 www 8458: }
8459:
8460: # --------------------------------------------------------------- Verify a symb
8461:
8462: sub symbverify {
1.510 www 8463: my ($symb,$thisurl)=@_;
8464: my $thisfn=$thisurl;
1.439 www 8465: $thisfn=&declutter($thisfn);
1.215 www 8466: # direct jump to resource in page or to a sequence - will construct own symbs
8467: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8468: # check URL part
1.409 www 8469: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8470:
1.431 www 8471: unless ($url eq $thisfn) { return 0; }
1.213 www 8472:
1.216 www 8473: $symb=&symbclean($symb);
1.510 www 8474: $thisurl=&deversion($thisurl);
1.439 www 8475: $thisfn=&deversion($thisfn);
1.213 www 8476:
8477: my %bighash;
8478: my $okay=0;
1.431 www 8479:
1.620 albertel 8480: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8481: &GDBM_READER(),0640)) {
1.1032 raeburn 8482: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8483: $thisurl =~ s/\?.+$//;
8484: }
1.510 www 8485: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8486: unless ($ids) {
1.510 www 8487: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8488: }
8489: if ($ids) {
8490: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8491: foreach my $id (split(/\,/,$ids)) {
8492: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8493: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8494: $symb =~ s/\?.+$//;
8495: }
1.216 www 8496: if (
8497: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8498: eq $symb) {
1.620 albertel 8499: if (($env{'request.role.adv'}) ||
1.800 albertel 8500: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8501: $okay=1;
8502: }
8503: }
1.216 www 8504: }
8505: }
1.213 www 8506: untie(%bighash);
8507: }
8508: return $okay;
1.31 www 8509: }
8510:
1.210 www 8511: # --------------------------------------------------------------- Clean-up symb
8512:
8513: sub symbclean {
8514: my $symb=shift;
1.568 albertel 8515: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8516: # remove version from map
8517: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8518:
1.210 www 8519: # remove version from URL
8520: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8521:
1.507 www 8522: # remove wrapper
8523:
1.510 www 8524: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8525: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8526: return $symb;
1.409 www 8527: }
8528:
8529: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8530:
8531: sub encode_symb {
8532: my ($map,$resid,$url)=@_;
8533: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8534: }
1.409 www 8535:
8536: sub decode_symb {
1.568 albertel 8537: my $symb=shift;
8538: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8539: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8540: return (&fixversion($map),$resid,&fixversion($url));
8541: }
8542:
8543: sub fixversion {
8544: my $fn=shift;
1.609 banghart 8545: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8546: my %bighash;
8547: my $uri=&clutter($fn);
1.620 albertel 8548: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8549: # is this cached?
1.599 albertel 8550: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8551: if (defined($cached)) { return $result; }
8552: # unfortunately not cached, or expired
1.620 albertel 8553: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8554: &GDBM_READER(),0640)) {
8555: if ($bighash{'version_'.$uri}) {
8556: my $version=$bighash{'version_'.$uri};
1.444 www 8557: unless (($version eq 'mostrecent') ||
8558: ($version==&getversion($uri))) {
1.440 www 8559: $uri=~s/\.(\w+)$/\.$version\.$1/;
8560: }
8561: }
8562: untie %bighash;
1.413 www 8563: }
1.599 albertel 8564: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8565: }
8566:
8567: sub deversion {
8568: my $url=shift;
8569: $url=~s/\.\d+\.(\w+)$/\.$1/;
8570: return $url;
1.210 www 8571: }
8572:
1.31 www 8573: # ------------------------------------------------------ Return symb list entry
8574:
8575: sub symbread {
1.249 www 8576: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8577: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8578: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8579: # no filename provided? try from environment
1.44 www 8580: unless ($thisfn) {
1.620 albertel 8581: if ($env{'request.symb'}) {
8582: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8583: }
1.620 albertel 8584: $thisfn=$env{'request.filename'};
1.44 www 8585: }
1.569 albertel 8586: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8587: # is that filename actually a symb? Verify, clean, and return
8588: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8589: if (&symbverify($thisfn,$1)) {
1.620 albertel 8590: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8591: }
1.242 www 8592: }
1.44 www 8593: $thisfn=declutter($thisfn);
1.31 www 8594: my %hash;
1.37 www 8595: my %bighash;
8596: my $syval='';
1.620 albertel 8597: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8598: my $targetfn = $thisfn;
1.609 banghart 8599: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8600: $targetfn = 'adm/wrapper/'.$thisfn;
8601: }
1.687 albertel 8602: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8603: $targetfn=$1;
8604: }
1.620 albertel 8605: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8606: &GDBM_READER(),0640)) {
1.481 raeburn 8607: $syval=$hash{$targetfn};
1.37 www 8608: untie(%hash);
8609: }
8610: # ---------------------------------------------------------- There was an entry
8611: if ($syval) {
1.601 albertel 8612: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8613: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8614: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8615: #return $env{$cache_str}='';
1.601 albertel 8616: #}
8617: #$syval.=$1;
8618: #}
1.37 www 8619: } else {
8620: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8621: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8622: &GDBM_READER(),0640)) {
1.37 www 8623: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8624: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8625: unless ($ids) {
8626: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8627: }
8628: unless ($ids) {
8629: # alias?
8630: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8631: }
1.37 www 8632: if ($ids) {
8633: # ------------------------------------------------------------------- Has ID(s)
8634: my @possibilities=split(/\,/,$ids);
1.39 www 8635: if ($#possibilities==0) {
8636: # ----------------------------------------------- There is only one possibility
1.37 www 8637: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8638: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8639: $resid,$thisfn);
1.249 www 8640: } elsif (!$donotrecurse) {
1.39 www 8641: # ------------------------------------------ There is more than one possibility
8642: my $realpossible=0;
1.800 albertel 8643: foreach my $id (@possibilities) {
8644: my $file=$bighash{'src_'.$id};
1.39 www 8645: if (&allowed('bre',$file)) {
1.800 albertel 8646: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8647: if ($bighash{'map_type_'.$mapid} ne 'page') {
8648: $realpossible++;
1.626 albertel 8649: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8650: $resid,$thisfn);
1.39 www 8651: }
8652: }
1.191 harris41 8653: }
1.39 www 8654: if ($realpossible!=1) { $syval=''; }
1.249 www 8655: } else {
8656: $syval='';
1.37 www 8657: }
8658: }
8659: untie(%bighash)
1.481 raeburn 8660: }
1.31 www 8661: }
1.62 www 8662: if ($syval) {
1.620 albertel 8663: return $env{$cache_str}=$syval;
1.62 www 8664: }
1.31 www 8665: }
1.949 raeburn 8666: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8667: return $env{$cache_str}='';
1.31 www 8668: }
8669:
8670: # ---------------------------------------------------------- Return random seed
8671:
1.32 www 8672: sub numval {
8673: my $txt=shift;
8674: $txt=~tr/A-J/0-9/;
8675: $txt=~tr/a-j/0-9/;
8676: $txt=~tr/K-T/0-9/;
8677: $txt=~tr/k-t/0-9/;
8678: $txt=~tr/U-Z/0-5/;
8679: $txt=~tr/u-z/0-5/;
8680: $txt=~s/\D//g;
1.564 albertel 8681: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8682: return int($txt);
1.368 albertel 8683: }
8684:
1.484 albertel 8685: sub numval2 {
8686: my $txt=shift;
8687: $txt=~tr/A-J/0-9/;
8688: $txt=~tr/a-j/0-9/;
8689: $txt=~tr/K-T/0-9/;
8690: $txt=~tr/k-t/0-9/;
8691: $txt=~tr/U-Z/0-5/;
8692: $txt=~tr/u-z/0-5/;
8693: $txt=~s/\D//g;
8694: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8695: my $total;
8696: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8697: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8698: return int($total);
8699: }
8700:
1.575 albertel 8701: sub numval3 {
8702: use integer;
8703: my $txt=shift;
8704: $txt=~tr/A-J/0-9/;
8705: $txt=~tr/a-j/0-9/;
8706: $txt=~tr/K-T/0-9/;
8707: $txt=~tr/k-t/0-9/;
8708: $txt=~tr/U-Z/0-5/;
8709: $txt=~tr/u-z/0-5/;
8710: $txt=~s/\D//g;
8711: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8712: my $total;
8713: foreach my $val (@txts) { $total+=$val; }
8714: if ($_64bit) { $total=(($total<<32)>>32); }
8715: return $total;
8716: }
8717:
1.675 albertel 8718: sub digest {
8719: my ($data)=@_;
8720: my $digest=&Digest::MD5::md5($data);
8721: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8722: my ($e,$f);
8723: {
8724: use integer;
8725: $e=($a+$b);
8726: $f=($c+$d);
8727: if ($_64bit) {
8728: $e=(($e<<32)>>32);
8729: $f=(($f<<32)>>32);
8730: }
8731: }
8732: if (wantarray) {
8733: return ($e,$f);
8734: } else {
8735: my $g;
8736: {
8737: use integer;
8738: $g=($e+$f);
8739: if ($_64bit) {
8740: $g=(($g<<32)>>32);
8741: }
8742: }
8743: return $g;
8744: }
8745: }
8746:
1.368 albertel 8747: sub latest_rnd_algorithm_id {
1.675 albertel 8748: return '64bit5';
1.366 albertel 8749: }
1.32 www 8750:
1.503 albertel 8751: sub get_rand_alg {
8752: my ($courseid)=@_;
1.790 albertel 8753: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8754: if ($courseid) {
1.620 albertel 8755: return $env{"course.$courseid.rndseed"};
1.503 albertel 8756: }
8757: return &latest_rnd_algorithm_id();
8758: }
8759:
1.562 albertel 8760: sub validCODE {
8761: my ($CODE)=@_;
8762: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8763: return 0;
8764: }
8765:
1.491 albertel 8766: sub getCODE {
1.620 albertel 8767: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8768: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8769: defined($Apache::lonhomework::parsing_a_task) ) &&
8770: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8771: return $Apache::lonhomework::history{'resource.CODE'};
8772: }
8773: return undef;
8774: }
8775:
1.31 www 8776: sub rndseed {
1.155 albertel 8777: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8778: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8779: if (!defined($symb)) {
1.366 albertel 8780: unless ($symb=$wsymb) { return time; }
8781: }
8782: if (!$courseid) { $courseid=$wcourseid; }
8783: if (!$domain) { $domain=$wdomain; }
8784: if (!$username) { $username=$wusername }
1.503 albertel 8785: my $which=&get_rand_alg();
1.803 albertel 8786:
1.491 albertel 8787: if (defined(&getCODE())) {
1.675 albertel 8788: if ($which eq '64bit5') {
8789: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8790: } elsif ($which eq '64bit4') {
1.575 albertel 8791: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8792: } else {
8793: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8794: }
1.675 albertel 8795: } elsif ($which eq '64bit5') {
8796: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8797: } elsif ($which eq '64bit4') {
8798: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8799: } elsif ($which eq '64bit3') {
8800: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8801: } elsif ($which eq '64bit2') {
8802: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8803: } elsif ($which eq '64bit') {
8804: return &rndseed_64bit($symb,$courseid,$domain,$username);
8805: }
8806: return &rndseed_32bit($symb,$courseid,$domain,$username);
8807: }
8808:
8809: sub rndseed_32bit {
8810: my ($symb,$courseid,$domain,$username)=@_;
8811: {
8812: use integer;
8813: my $symbchck=unpack("%32C*",$symb) << 27;
8814: my $symbseed=numval($symb) << 22;
8815: my $namechck=unpack("%32C*",$username) << 17;
8816: my $nameseed=numval($username) << 12;
8817: my $domainseed=unpack("%32C*",$domain) << 7;
8818: my $courseseed=unpack("%32C*",$courseid);
8819: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8820: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8821: #&logthis("rndseed :$num:$symb");
1.564 albertel 8822: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8823: return $num;
8824: }
8825: }
8826:
8827: sub rndseed_64bit {
8828: my ($symb,$courseid,$domain,$username)=@_;
8829: {
8830: use integer;
8831: my $symbchck=unpack("%32S*",$symb) << 21;
8832: my $symbseed=numval($symb) << 10;
8833: my $namechck=unpack("%32S*",$username);
8834:
8835: my $nameseed=numval($username) << 21;
8836: my $domainseed=unpack("%32S*",$domain) << 10;
8837: my $courseseed=unpack("%32S*",$courseid);
8838:
8839: my $num1=$symbchck+$symbseed+$namechck;
8840: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8841: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8842: #&logthis("rndseed :$num:$symb");
1.564 albertel 8843: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8844: return "$num1,$num2";
1.155 albertel 8845: }
1.366 albertel 8846: }
8847:
1.443 albertel 8848: sub rndseed_64bit2 {
8849: my ($symb,$courseid,$domain,$username)=@_;
8850: {
8851: use integer;
8852: # strings need to be an even # of cahracters long, it it is odd the
8853: # last characters gets thrown away
8854: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8855: my $symbseed=numval($symb) << 10;
8856: my $namechck=unpack("%32S*",$username.' ');
8857:
8858: my $nameseed=numval($username) << 21;
1.501 albertel 8859: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8860: my $courseseed=unpack("%32S*",$courseid.' ');
8861:
8862: my $num1=$symbchck+$symbseed+$namechck;
8863: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8864: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8865: #&logthis("rndseed :$num:$symb");
1.803 albertel 8866: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8867: return "$num1,$num2";
8868: }
8869: }
8870:
8871: sub rndseed_64bit3 {
8872: my ($symb,$courseid,$domain,$username)=@_;
8873: {
8874: use integer;
8875: # strings need to be an even # of cahracters long, it it is odd the
8876: # last characters gets thrown away
8877: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8878: my $symbseed=numval2($symb) << 10;
8879: my $namechck=unpack("%32S*",$username.' ');
8880:
8881: my $nameseed=numval2($username) << 21;
1.443 albertel 8882: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8883: my $courseseed=unpack("%32S*",$courseid.' ');
8884:
8885: my $num1=$symbchck+$symbseed+$namechck;
8886: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8887: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8888: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8889: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8890:
1.503 albertel 8891: return "$num1:$num2";
1.443 albertel 8892: }
8893: }
8894:
1.575 albertel 8895: sub rndseed_64bit4 {
8896: my ($symb,$courseid,$domain,$username)=@_;
8897: {
8898: use integer;
8899: # strings need to be an even # of cahracters long, it it is odd the
8900: # last characters gets thrown away
8901: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8902: my $symbseed=numval3($symb) << 10;
8903: my $namechck=unpack("%32S*",$username.' ');
8904:
8905: my $nameseed=numval3($username) << 21;
8906: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8907: my $courseseed=unpack("%32S*",$courseid.' ');
8908:
8909: my $num1=$symbchck+$symbseed+$namechck;
8910: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8911: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8912: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8913: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8914:
8915: return "$num1:$num2";
8916: }
8917: }
8918:
1.675 albertel 8919: sub rndseed_64bit5 {
8920: my ($symb,$courseid,$domain,$username)=@_;
8921: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8922: return "$num1:$num2";
8923: }
8924:
1.366 albertel 8925: sub rndseed_CODE_64bit {
8926: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8927: {
1.366 albertel 8928: use integer;
1.443 albertel 8929: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8930: my $symbseed=numval2($symb);
1.491 albertel 8931: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8932: my $CODEseed=numval(&getCODE());
1.443 albertel 8933: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8934: my $num1=$symbseed+$CODEchck;
8935: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8936: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8937: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8938: if ($_64bit) { $num1=(($num1<<32)>>32); }
8939: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8940: return "$num1:$num2";
1.366 albertel 8941: }
8942: }
8943:
1.575 albertel 8944: sub rndseed_CODE_64bit4 {
8945: my ($symb,$courseid,$domain,$username)=@_;
8946: {
8947: use integer;
8948: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8949: my $symbseed=numval3($symb);
8950: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8951: my $CODEseed=numval3(&getCODE());
8952: my $courseseed=unpack("%32S*",$courseid.' ');
8953: my $num1=$symbseed+$CODEchck;
8954: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8955: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8956: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8957: if ($_64bit) { $num1=(($num1<<32)>>32); }
8958: if ($_64bit) { $num2=(($num2<<32)>>32); }
8959: return "$num1:$num2";
8960: }
8961: }
8962:
1.675 albertel 8963: sub rndseed_CODE_64bit5 {
8964: my ($symb,$courseid,$domain,$username)=@_;
8965: my $code = &getCODE();
8966: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8967: return "$num1:$num2";
8968: }
8969:
1.366 albertel 8970: sub setup_random_from_rndseed {
8971: my ($rndseed)=@_;
1.503 albertel 8972: if ($rndseed =~/([,:])/) {
8973: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8974: &Math::Random::random_set_seed(abs($num1),abs($num2));
8975: } else {
8976: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8977: }
1.36 albertel 8978: }
8979:
1.474 albertel 8980: sub latest_receipt_algorithm_id {
1.835 albertel 8981: return 'receipt3';
1.474 albertel 8982: }
8983:
1.480 www 8984: sub recunique {
8985: my $fucourseid=shift;
8986: my $unique;
1.835 albertel 8987: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8988: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8989: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8990: } else {
8991: $unique=$perlvar{'lonReceipt'};
8992: }
8993: return unpack("%32C*",$unique);
8994: }
8995:
8996: sub recprefix {
8997: my $fucourseid=shift;
8998: my $prefix;
1.835 albertel 8999: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9000: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9001: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9002: } else {
9003: $prefix=$perlvar{'lonHostID'};
9004: }
9005: return unpack("%32C*",$prefix);
9006: }
9007:
1.76 www 9008: sub ireceipt {
1.474 albertel 9009: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9010:
9011: my $return =&recprefix($fucourseid).'-';
9012:
9013: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9014: $env{'request.state'} eq 'construct') {
9015: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9016: return $return;
9017: }
9018:
1.76 www 9019: my $cuname=unpack("%32C*",$funame);
9020: my $cudom=unpack("%32C*",$fudom);
9021: my $cucourseid=unpack("%32C*",$fucourseid);
9022: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9023: my $cunique=&recunique($fucourseid);
1.474 albertel 9024: my $cpart=unpack("%32S*",$part);
1.835 albertel 9025: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9026:
1.790 albertel 9027: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9028:
9029: $return.= ($cunique%$cuname+
9030: $cunique%$cudom+
9031: $cusymb%$cuname+
9032: $cusymb%$cudom+
9033: $cucourseid%$cuname+
9034: $cucourseid%$cudom+
9035: $cpart%$cuname+
9036: $cpart%$cudom);
9037: } else {
9038: $return.= ($cunique%$cuname+
9039: $cunique%$cudom+
9040: $cusymb%$cuname+
9041: $cusymb%$cudom+
9042: $cucourseid%$cuname+
9043: $cucourseid%$cudom);
9044: }
9045: return $return;
1.76 www 9046: }
9047:
9048: sub receipt {
1.474 albertel 9049: my ($part)=@_;
1.790 albertel 9050: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9051: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9052: }
1.260 ng 9053:
1.790 albertel 9054: sub whichuser {
9055: my ($passedsymb)=@_;
9056: my ($symb,$courseid,$domain,$name,$publicuser);
9057: if (defined($env{'form.grade_symb'})) {
9058: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9059: my $allowed=&allowed('vgr',$tmp_courseid);
9060: if (!$allowed &&
9061: exists($env{'request.course.sec'}) &&
9062: $env{'request.course.sec'} !~ /^\s*$/) {
9063: $allowed=&allowed('vgr',$tmp_courseid.
9064: '/'.$env{'request.course.sec'});
9065: }
9066: if ($allowed) {
9067: ($symb)=&get_env_multiple('form.grade_symb');
9068: $courseid=$tmp_courseid;
9069: ($domain)=&get_env_multiple('form.grade_domain');
9070: ($name)=&get_env_multiple('form.grade_username');
9071: return ($symb,$courseid,$domain,$name,$publicuser);
9072: }
9073: }
9074: if (!$passedsymb) {
9075: $symb=&symbread();
9076: } else {
9077: $symb=$passedsymb;
9078: }
9079: $courseid=$env{'request.course.id'};
9080: $domain=$env{'user.domain'};
9081: $name=$env{'user.name'};
9082: if ($name eq 'public' && $domain eq 'public') {
9083: if (!defined($env{'form.username'})) {
9084: $env{'form.username'}.=time.rand(10000000);
9085: }
9086: $name.=$env{'form.username'};
9087: }
9088: return ($symb,$courseid,$domain,$name,$publicuser);
9089:
9090: }
9091:
1.36 albertel 9092: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9093: # returns either the contents of the file or
9094: # -1 if the file doesn't exist
1.481 raeburn 9095: #
9096: # if the target is a file that was uploaded via DOCS,
9097: # a check will be made to see if a current copy exists on the local server,
9098: # if it does this will be served, otherwise a copy will be retrieved from
9099: # the home server for the course and stored in /home/httpd/html/userfiles on
9100: # the local server.
1.472 albertel 9101:
1.36 albertel 9102: sub getfile {
1.538 albertel 9103: my ($file) = @_;
1.609 banghart 9104: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9105: &repcopy($file);
9106: return &readfile($file);
9107: }
9108:
9109: sub repcopy_userfile {
9110: my ($file)=@_;
1.609 banghart 9111: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9112: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9113: my ($cdom,$cnum,$filename) =
1.811 albertel 9114: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9115: my $uri="/uploaded/$cdom/$cnum/$filename";
9116: if (-e "$file") {
1.828 www 9117: # we already have a local copy, check it out
1.538 albertel 9118: my @fileinfo = stat($file);
1.828 www 9119: my $rtncode;
9120: my $info;
1.538 albertel 9121: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9122: if ($lwpresp ne 'ok') {
1.828 www 9123: # there is no such file anymore, even though we had a local copy
1.482 albertel 9124: if ($rtncode eq '404') {
1.538 albertel 9125: unlink($file);
1.482 albertel 9126: }
9127: return -1;
9128: }
9129: if ($info < $fileinfo[9]) {
1.828 www 9130: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9131: return 'ok';
1.828 www 9132: } else {
9133: # the file is outdated, get rid of it
9134: unlink($file);
1.482 albertel 9135: }
1.828 www 9136: }
9137: # one way or the other, at this point, we don't have the file
9138: # construct the correct path for the file
9139: my @parts = ($cdom,$cnum);
9140: if ($filename =~ m|^(.+)/[^/]+$|) {
9141: push @parts, split(/\//,$1);
9142: }
9143: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9144: foreach my $part (@parts) {
9145: $path .= '/'.$part;
9146: if (!-e $path) {
9147: mkdir($path,0770);
1.482 albertel 9148: }
9149: }
1.828 www 9150: # now the path exists for sure
9151: # get a user agent
9152: my $ua=new LWP::UserAgent;
9153: my $transferfile=$file.'.in.transfer';
9154: # FIXME: this should flock
9155: if (-e $transferfile) { return 'ok'; }
9156: my $request;
9157: $uri=~s/^\///;
1.980 raeburn 9158: my $homeserver = &homeserver($cnum,$cdom);
9159: my $protocol = $protocol{$homeserver};
9160: $protocol = 'http' if ($protocol ne 'https');
9161: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9162: my $response=$ua->request($request,$transferfile);
9163: # did it work?
9164: if ($response->is_error()) {
9165: unlink($transferfile);
9166: &logthis("Userfile repcopy failed for $uri");
9167: return -1;
9168: }
9169: # worked, rename the transfer file
9170: rename($transferfile,$file);
1.607 raeburn 9171: return 'ok';
1.481 raeburn 9172: }
9173:
1.517 albertel 9174: sub tokenwrapper {
9175: my $uri=shift;
1.980 raeburn 9176: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9177: $uri=~s|^/||;
1.620 albertel 9178: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9179: my $token=$1;
1.552 albertel 9180: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9181: if ($udom && $uname && $file) {
9182: $file=~s|(\?\.*)*$||;
1.949 raeburn 9183: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9184: my $homeserver = &homeserver($uname,$udom);
9185: my $protocol = $protocol{$homeserver};
9186: $protocol = 'http' if ($protocol ne 'https');
9187: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9188: (($uri=~/\?/)?'&':'?').'token='.$token.
9189: '&tokenissued='.$perlvar{'lonHostID'};
9190: } else {
9191: return '/adm/notfound.html';
9192: }
9193: }
9194:
1.828 www 9195: # call with reqtype HEAD: get last modification time
9196: # call with reqtype GET: get the file contents
9197: # Do not call this with reqtype GET for large files! It loads everything into memory
9198: #
1.481 raeburn 9199: sub getuploaded {
9200: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9201: $uri=~s/^\///;
1.980 raeburn 9202: my $homeserver = &homeserver($cnum,$cdom);
9203: my $protocol = $protocol{$homeserver};
9204: $protocol = 'http' if ($protocol ne 'https');
9205: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9206: my $ua=new LWP::UserAgent;
9207: my $request=new HTTP::Request($reqtype,$uri);
9208: my $response=$ua->request($request);
9209: $$rtncode = $response->code;
1.482 albertel 9210: if (! $response->is_success()) {
9211: return 'failed';
9212: }
9213: if ($reqtype eq 'HEAD') {
1.486 www 9214: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9215: } elsif ($reqtype eq 'GET') {
9216: $$info = $response->content;
1.472 albertel 9217: }
1.482 albertel 9218: return 'ok';
1.36 albertel 9219: }
9220:
1.481 raeburn 9221: sub readfile {
9222: my $file = shift;
9223: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9224: my $fh;
9225: open($fh,"<$file");
9226: my $a='';
1.800 albertel 9227: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9228: return $a;
9229: }
9230:
1.36 albertel 9231: sub filelocation {
1.590 banghart 9232: my ($dir,$file) = @_;
9233: my $location;
9234: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9235:
9236: if ($file =~ m-^/adm/-) {
9237: $file=~s-^/adm/wrapper/-/-;
9238: $file=~s-^/adm/coursedocs/showdoc/-/-;
9239: }
1.882 albertel 9240:
1.590 banghart 9241: if ($file=~m:^/~:) { # is a contruction space reference
9242: $location = $file;
9243: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9244: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9245: # is a correct contruction space reference
9246: $location = $file;
1.956 raeburn 9247: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9248: $location = $file;
1.609 banghart 9249: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9250: my ($udom,$uname,$filename)=
1.811 albertel 9251: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9252: my $home=&homeserver($uname,$udom);
9253: my $is_me=0;
9254: my @ids=¤t_machine_ids();
9255: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9256: if ($is_me) {
1.955 raeburn 9257: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9258: } else {
9259: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9260: $udom.'/'.$uname.'/'.$filename;
9261: }
1.882 albertel 9262: } elsif ($file =~ m-^/adm/-) {
9263: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9264: } else {
9265: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9266: $file=~s:^/res/:/:;
9267: if ( !( $file =~ m:^/:) ) {
9268: $location = $dir. '/'.$file;
9269: } else {
9270: $location = '/home/httpd/html/res'.$file;
9271: }
1.59 albertel 9272: }
1.590 banghart 9273: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9274: while ($location=~m{/\.\./}) {
9275: if ($location =~ m{/[^/]+/\.\./}) {
9276: $location=~ s{/[^/]+/\.\./}{/}g;
9277: } else {
9278: $location=~ s{/\.\./}{/}g;
9279: }
9280: } #remove dir/..
1.590 banghart 9281: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9282: return $location;
1.46 www 9283: }
1.36 albertel 9284:
1.46 www 9285: sub hreflocation {
9286: my ($dir,$file)=@_;
1.980 raeburn 9287: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9288: $file=filelocation($dir,$file);
1.700 albertel 9289: } elsif ($file=~m-^/adm/-) {
9290: $file=~s-^/adm/wrapper/-/-;
9291: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9292: }
9293: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9294: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9295: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9296: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9297: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9298: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9299: -/uploaded/$1/$2/-x;
1.46 www 9300: }
1.913 albertel 9301: if ($file=~ m{^/userfiles/}) {
9302: $file =~ s{^/userfiles/}{/uploaded/};
9303: }
1.462 albertel 9304: return $file;
1.465 albertel 9305: }
9306:
9307: sub current_machine_domains {
1.853 albertel 9308: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9309: }
9310:
9311: sub machine_domains {
9312: my ($hostname) = @_;
1.465 albertel 9313: my @domains;
1.838 albertel 9314: my %hostname = &all_hostnames();
1.465 albertel 9315: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9316: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9317: if ($hostname eq $name) {
1.844 albertel 9318: push(@domains,&host_domain($id));
1.465 albertel 9319: }
9320: }
9321: return @domains;
9322: }
9323:
9324: sub current_machine_ids {
1.853 albertel 9325: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9326: }
9327:
9328: sub machine_ids {
9329: my ($hostname) = @_;
9330: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9331: my @ids;
1.888 albertel 9332: my %name_to_host = &all_names();
1.889 albertel 9333: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9334: return @{ $name_to_host{$hostname} };
9335: }
9336: return;
1.31 www 9337: }
9338:
1.824 raeburn 9339: sub additional_machine_domains {
9340: my @domains;
9341: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9342: while( my $line = <$fh>) {
9343: $line =~ s/\s//g;
9344: push(@domains,$line);
9345: }
9346: return @domains;
9347: }
9348:
9349: sub default_login_domain {
9350: my $domain = $perlvar{'lonDefDomain'};
9351: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9352: foreach my $posdom (¤t_machine_domains(),
9353: &additional_machine_domains()) {
9354: if (lc($posdom) eq lc($testdomain)) {
9355: $domain=$posdom;
9356: last;
9357: }
9358: }
9359: return $domain;
9360: }
9361:
1.31 www 9362: # ------------------------------------------------------------- Declutters URLs
9363:
9364: sub declutter {
9365: my $thisfn=shift;
1.569 albertel 9366: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9367: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9368: $thisfn=~s/^\///;
1.697 albertel 9369: $thisfn=~s|^adm/wrapper/||;
9370: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9371: $thisfn=~s/^res\///;
1.1032 raeburn 9372: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9373: $thisfn=~s/\?.+$//;
9374: }
1.268 www 9375: return $thisfn;
9376: }
9377:
9378: # ------------------------------------------------------------- Clutter up URLs
9379:
9380: sub clutter {
9381: my $thisfn='/'.&declutter(shift);
1.887 albertel 9382: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9383: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9384: $thisfn='/res'.$thisfn;
9385: }
1.1031 raeburn 9386: if ($thisfn !~m|^/adm|) {
9387: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9388: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9389: } else {
9390: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9391: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9392: if ($embstyle eq 'ssi'
9393: || ($embstyle eq 'hdn')
9394: || ($embstyle eq 'rat')
9395: || ($embstyle eq 'prv')
9396: || ($embstyle eq 'ign')) {
9397: #do nothing with these
9398: } elsif (($embstyle eq 'img')
1.695 albertel 9399: || ($embstyle eq 'emb')
9400: || ($embstyle eq 'wrp')) {
9401: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9402: } elsif ($embstyle eq 'unk'
9403: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9404: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9405: } else {
1.718 www 9406: # &logthis("Got a blank emb style");
1.695 albertel 9407: }
1.694 albertel 9408: }
9409: }
1.31 www 9410: return $thisfn;
1.12 www 9411: }
9412:
1.787 albertel 9413: sub clutter_with_no_wrapper {
9414: my $uri = &clutter(shift);
9415: if ($uri =~ m-^/adm/-) {
9416: $uri =~ s-^/adm/wrapper/-/-;
9417: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9418: }
9419: return $uri;
9420: }
9421:
1.557 albertel 9422: sub freeze_escape {
9423: my ($value)=@_;
9424: if (ref($value)) {
9425: $value=&nfreeze($value);
9426: return '__FROZEN__'.&escape($value);
9427: }
9428: return &escape($value);
9429: }
9430:
1.11 www 9431:
1.557 albertel 9432: sub thaw_unescape {
9433: my ($value)=@_;
9434: if ($value =~ /^__FROZEN__/) {
9435: substr($value,0,10,undef);
9436: $value=&unescape($value);
9437: return &thaw($value);
9438: }
9439: return &unescape($value);
9440: }
9441:
1.436 albertel 9442: sub correct_line_ends {
9443: my ($result)=@_;
9444: $$result =~s/\r\n/\n/mg;
9445: $$result =~s/\r/\n/mg;
1.415 albertel 9446: }
1.1 albertel 9447: # ================================================================ Main Program
9448:
1.184 www 9449: sub goodbye {
1.204 albertel 9450: &logthis("Starting Shut down");
1.443 albertel 9451: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9452: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9453: #converted
1.599 albertel 9454: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9455: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9456: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9457: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9458: #1.1 only
1.870 albertel 9459: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9460: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9461: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9462: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9463: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9464: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9465: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9466: &flushcourselogs();
9467: &logthis("Shutting down");
9468: }
9469:
1.852 albertel 9470: sub get_dns {
1.869 albertel 9471: my ($url,$func,$ignore_cache) = @_;
9472: if (!$ignore_cache) {
9473: my ($content,$cached)=
9474: &Apache::lonnet::is_cached_new('dns',$url);
9475: if ($cached) {
9476: &$func($content);
9477: return;
9478: }
9479: }
9480:
9481: my %alldns;
1.852 albertel 9482: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9483: foreach my $dns (<$config>) {
9484: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9485: my $line = $1;
9486: my ($host,$protocol) = split(/:/,$line);
9487: if ($protocol ne 'https') {
9488: $protocol = 'http';
9489: }
9490: $alldns{$host} = $protocol;
1.869 albertel 9491: }
9492: while (%alldns) {
9493: my ($dns) = keys(%alldns);
1.852 albertel 9494: my $ua=new LWP::UserAgent;
1.979 raeburn 9495: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9496: my $response=$ua->request($request);
1.979 raeburn 9497: delete($alldns{$dns});
1.852 albertel 9498: next if ($response->is_error());
9499: my @content = split("\n",$response->content);
1.869 albertel 9500: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9501: &$func(\@content);
1.869 albertel 9502: return;
1.852 albertel 9503: }
9504: close($config);
1.871 albertel 9505: my $which = (split('/',$url))[3];
9506: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9507: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9508: my @content = <$config>;
9509: &$func(\@content);
9510: return;
1.852 albertel 9511: }
1.327 albertel 9512: # ------------------------------------------------------------ Read domain file
9513: {
1.852 albertel 9514: my $loaded;
1.846 albertel 9515: my %domain;
9516:
1.852 albertel 9517: sub parse_domain_tab {
9518: my ($lines) = @_;
9519: foreach my $line (@$lines) {
9520: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9521:
1.846 albertel 9522: chomp($line);
1.852 albertel 9523: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9524: my %this_domain;
9525: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9526: 'lang_def', 'city', 'longi', 'lati',
9527: 'primary') {
9528: $this_domain{$field} = shift(@elements);
9529: }
9530: $domain{$name} = \%this_domain;
1.852 albertel 9531: }
9532: }
1.864 albertel 9533:
9534: sub reset_domain_info {
9535: undef($loaded);
9536: undef(%domain);
9537: }
9538:
1.852 albertel 9539: sub load_domain_tab {
1.869 albertel 9540: my ($ignore_cache) = @_;
9541: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9542: my $fh;
9543: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9544: my @lines = <$fh>;
9545: &parse_domain_tab(\@lines);
1.448 albertel 9546: }
1.852 albertel 9547: close($fh);
9548: $loaded = 1;
1.327 albertel 9549: }
1.846 albertel 9550:
9551: sub domain {
1.852 albertel 9552: &load_domain_tab() if (!$loaded);
9553:
1.846 albertel 9554: my ($name,$what) = @_;
9555: return if ( !exists($domain{$name}) );
9556:
9557: if (!$what) {
9558: return $domain{$name}{'description'};
9559: }
9560: return $domain{$name}{$what};
9561: }
1.974 raeburn 9562:
9563: sub domain_info {
9564: &load_domain_tab() if (!$loaded);
9565: return %domain;
9566: }
9567:
1.327 albertel 9568: }
9569:
9570:
1.1 albertel 9571: # ------------------------------------------------------------- Read hosts file
9572: {
1.838 albertel 9573: my %hostname;
1.844 albertel 9574: my %hostdom;
1.845 albertel 9575: my %libserv;
1.852 albertel 9576: my $loaded;
1.888 albertel 9577: my %name_to_host;
1.852 albertel 9578:
9579: sub parse_hosts_tab {
9580: my ($file) = @_;
9581: foreach my $configline (@$file) {
9582: next if ($configline =~ /^(\#|\s*$ )/x);
9583: next if ($configline =~ /^\^/);
9584: chomp($configline);
1.968 raeburn 9585: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9586: $name=~s/\s//g;
9587: if ($id && $domain && $role && $name) {
9588: $hostname{$id}=$name;
1.888 albertel 9589: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9590: $hostdom{$id}=$domain;
9591: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9592: if (defined($protocol)) {
9593: if ($protocol eq 'https') {
9594: $protocol{$id} = $protocol;
9595: } else {
9596: $protocol{$id} = 'http';
9597: }
1.968 raeburn 9598: } else {
1.969 raeburn 9599: $protocol{$id} = 'http';
1.968 raeburn 9600: }
1.852 albertel 9601: }
9602: }
9603: }
1.864 albertel 9604:
9605: sub reset_hosts_info {
1.897 albertel 9606: &purge_remembered();
1.864 albertel 9607: &reset_domain_info();
9608: &reset_hosts_ip_info();
1.892 albertel 9609: undef(%name_to_host);
1.864 albertel 9610: undef(%hostname);
9611: undef(%hostdom);
9612: undef(%libserv);
9613: undef($loaded);
9614: }
1.1 albertel 9615:
1.852 albertel 9616: sub load_hosts_tab {
1.869 albertel 9617: my ($ignore_cache) = @_;
9618: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9619: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9620: my @config = <$config>;
9621: &parse_hosts_tab(\@config);
9622: close($config);
9623: $loaded=1;
1.1 albertel 9624: }
1.852 albertel 9625:
1.838 albertel 9626: sub hostname {
1.852 albertel 9627: &load_hosts_tab() if (!$loaded);
9628:
1.838 albertel 9629: my ($lonid) = @_;
9630: return $hostname{$lonid};
9631: }
1.845 albertel 9632:
1.838 albertel 9633: sub all_hostnames {
1.852 albertel 9634: &load_hosts_tab() if (!$loaded);
9635:
1.838 albertel 9636: return %hostname;
9637: }
1.845 albertel 9638:
1.888 albertel 9639: sub all_names {
9640: &load_hosts_tab() if (!$loaded);
9641:
9642: return %name_to_host;
9643: }
9644:
1.974 raeburn 9645: sub all_host_domain {
9646: &load_hosts_tab() if (!$loaded);
9647: return %hostdom;
9648: }
9649:
1.845 albertel 9650: sub is_library {
1.852 albertel 9651: &load_hosts_tab() if (!$loaded);
9652:
1.845 albertel 9653: return exists($libserv{$_[0]});
9654: }
9655:
9656: sub all_library {
1.852 albertel 9657: &load_hosts_tab() if (!$loaded);
9658:
1.845 albertel 9659: return %libserv;
9660: }
9661:
1.841 albertel 9662: sub get_servers {
1.852 albertel 9663: &load_hosts_tab() if (!$loaded);
9664:
1.841 albertel 9665: my ($domain,$type) = @_;
9666: my %possible_hosts = ($type eq 'library') ? %libserv
9667: : %hostname;
9668: my %result;
1.842 albertel 9669: if (ref($domain) eq 'ARRAY') {
9670: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9671: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9672: $result{$host} = $hostname;
9673: }
9674: }
9675: } else {
9676: while ( my ($host,$hostname) = each(%possible_hosts)) {
9677: if ($hostdom{$host} eq $domain) {
9678: $result{$host} = $hostname;
9679: }
1.841 albertel 9680: }
9681: }
9682: return %result;
9683: }
1.845 albertel 9684:
1.844 albertel 9685: sub host_domain {
1.852 albertel 9686: &load_hosts_tab() if (!$loaded);
9687:
1.844 albertel 9688: my ($lonid) = @_;
9689: return $hostdom{$lonid};
9690: }
9691:
1.841 albertel 9692: sub all_domains {
1.852 albertel 9693: &load_hosts_tab() if (!$loaded);
9694:
1.841 albertel 9695: my %seen;
9696: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9697: return @uniq;
9698: }
1.1 albertel 9699: }
9700:
1.847 albertel 9701: {
9702: my %iphost;
1.856 albertel 9703: my %name_to_ip;
9704: my %lonid_to_ip;
1.869 albertel 9705:
1.847 albertel 9706: sub get_hosts_from_ip {
9707: my ($ip) = @_;
9708: my %iphosts = &get_iphost();
9709: if (ref($iphosts{$ip})) {
9710: return @{$iphosts{$ip}};
9711: }
9712: return;
1.839 albertel 9713: }
1.864 albertel 9714:
9715: sub reset_hosts_ip_info {
9716: undef(%iphost);
9717: undef(%name_to_ip);
9718: undef(%lonid_to_ip);
9719: }
1.856 albertel 9720:
9721: sub get_host_ip {
9722: my ($lonid) = @_;
9723: if (exists($lonid_to_ip{$lonid})) {
9724: return $lonid_to_ip{$lonid};
9725: }
9726: my $name=&hostname($lonid);
9727: my $ip = gethostbyname($name);
9728: return if (!$ip || length($ip) ne 4);
9729: $ip=inet_ntoa($ip);
9730: $name_to_ip{$name} = $ip;
9731: $lonid_to_ip{$lonid} = $ip;
9732: return $ip;
9733: }
1.847 albertel 9734:
9735: sub get_iphost {
1.869 albertel 9736: my ($ignore_cache) = @_;
1.894 albertel 9737:
1.869 albertel 9738: if (!$ignore_cache) {
9739: if (%iphost) {
9740: return %iphost;
9741: }
9742: my ($ip_info,$cached)=
9743: &Apache::lonnet::is_cached_new('iphost','iphost');
9744: if ($cached) {
9745: %iphost = %{$ip_info->[0]};
9746: %name_to_ip = %{$ip_info->[1]};
9747: %lonid_to_ip = %{$ip_info->[2]};
9748: return %iphost;
9749: }
9750: }
1.894 albertel 9751:
9752: # get yesterday's info for fallback
9753: my %old_name_to_ip;
9754: my ($ip_info,$cached)=
9755: &Apache::lonnet::is_cached_new('iphost','iphost');
9756: if ($cached) {
9757: %old_name_to_ip = %{$ip_info->[1]};
9758: }
9759:
1.888 albertel 9760: my %name_to_host = &all_names();
9761: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9762: my $ip;
9763: if (!exists($name_to_ip{$name})) {
9764: $ip = gethostbyname($name);
9765: if (!$ip || length($ip) ne 4) {
1.894 albertel 9766: if (defined($old_name_to_ip{$name})) {
9767: $ip = $old_name_to_ip{$name};
9768: &logthis("Can't find $name defaulting to old $ip");
9769: } else {
9770: &logthis("Name $name no IP found");
9771: next;
9772: }
9773: } else {
9774: $ip=inet_ntoa($ip);
1.847 albertel 9775: }
9776: $name_to_ip{$name} = $ip;
9777: } else {
9778: $ip = $name_to_ip{$name};
1.653 albertel 9779: }
1.888 albertel 9780: foreach my $id (@{ $name_to_host{$name} }) {
9781: $lonid_to_ip{$id} = $ip;
9782: }
9783: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9784: }
1.869 albertel 9785: &Apache::lonnet::do_cache_new('iphost','iphost',
9786: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9787: 48*60*60);
1.869 albertel 9788:
1.847 albertel 9789: return %iphost;
1.598 albertel 9790: }
9791:
1.992 raeburn 9792: #
9793: # Given a DNS returns the loncapa host name for that DNS
9794: #
9795: sub host_from_dns {
9796: my ($dns) = @_;
9797: my @hosts;
9798: my $ip;
9799:
1.993 raeburn 9800: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9801: $ip = $name_to_ip{$dns};
9802: }
9803: if (!$ip) {
9804: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9805: if (length($ip) == 4) {
9806: $ip = &IO::Socket::inet_ntoa($ip);
9807: }
9808: }
9809: if ($ip) {
9810: @hosts = get_hosts_from_ip($ip);
9811: return $hosts[0];
9812: }
9813: return undef;
1.986 foxr 9814: }
1.992 raeburn 9815:
1.986 foxr 9816: }
9817:
1.862 albertel 9818: BEGIN {
9819:
9820: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9821: unless ($readit) {
9822: {
9823: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9824: %perlvar = (%perlvar,%{$configvars});
9825: }
9826:
9827:
1.1 albertel 9828: # ------------------------------------------------------ Read spare server file
9829: {
1.448 albertel 9830: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9831:
9832: while (my $configline=<$config>) {
9833: chomp($configline);
1.284 matthew 9834: if ($configline) {
1.784 albertel 9835: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9836: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9837: push(@{ $spareid{$type} }, $host);
1.1 albertel 9838: }
9839: }
1.448 albertel 9840: close($config);
1.1 albertel 9841: }
1.11 www 9842: # ------------------------------------------------------------ Read permissions
9843: {
1.448 albertel 9844: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9845:
9846: while (my $configline=<$config>) {
1.448 albertel 9847: chomp($configline);
9848: if ($configline) {
9849: my ($role,$perm)=split(/ /,$configline);
9850: if ($perm ne '') { $pr{$role}=$perm; }
9851: }
1.11 www 9852: }
1.448 albertel 9853: close($config);
1.11 www 9854: }
9855:
9856: # -------------------------------------------- Read plain texts for permissions
9857: {
1.448 albertel 9858: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9859:
9860: while (my $configline=<$config>) {
1.448 albertel 9861: chomp($configline);
9862: if ($configline) {
1.742 raeburn 9863: my ($short,@plain)=split(/:/,$configline);
9864: %{$prp{$short}} = ();
9865: if (@plain > 0) {
9866: $prp{$short}{'std'} = $plain[0];
9867: for (my $i=1; $i<@plain; $i++) {
9868: $prp{$short}{'alt'.$i} = $plain[$i];
9869: }
9870: }
1.448 albertel 9871: }
1.135 www 9872: }
1.448 albertel 9873: close($config);
1.135 www 9874: }
9875:
9876: # ---------------------------------------------------------- Read package table
9877: {
1.448 albertel 9878: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9879:
9880: while (my $configline=<$config>) {
1.483 albertel 9881: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9882: chomp($configline);
9883: my ($short,$plain)=split(/:/,$configline);
9884: my ($pack,$name)=split(/\&/,$short);
9885: if ($plain ne '') {
9886: $packagetab{$pack.'&'.$name.'&name'}=$name;
9887: $packagetab{$short}=$plain;
9888: }
1.11 www 9889: }
1.448 albertel 9890: close($config);
1.329 matthew 9891: }
9892:
9893: # ------------- set up temporary directory
9894: {
9895: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9896:
1.11 www 9897: }
9898:
1.794 albertel 9899: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9900: 'compress_threshold'=> 20_000,
9901: });
1.185 www 9902:
1.281 www 9903: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9904: $dumpcount=0;
1.958 www 9905: $locknum=0;
1.22 www 9906:
1.163 harris41 9907: &logtouch();
1.672 albertel 9908: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9909: $readit=1;
1.564 albertel 9910: {
9911: use integer;
9912: my $test=(2**32)+1;
1.568 albertel 9913: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9914: &logthis(" Detected 64bit platform ($_64bit)");
9915: }
1.195 www 9916: }
1.1 albertel 9917: }
1.179 www 9918:
1.1 albertel 9919: 1;
1.191 harris41 9920: __END__
9921:
1.243 albertel 9922: =pod
9923:
1.191 harris41 9924: =head1 NAME
9925:
1.243 albertel 9926: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9927:
9928: =head1 SYNOPSIS
9929:
1.243 albertel 9930: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9931:
9932: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9933:
1.243 albertel 9934: Common parameters:
9935:
9936: =over 4
9937:
9938: =item *
9939:
9940: $uname : an internal username (if $cname expecting a course Id specifically)
9941:
9942: =item *
9943:
9944: $udom : a domain (if $cdom expecting a course's domain specifically)
9945:
9946: =item *
9947:
9948: $symb : a resource instance identifier
9949:
9950: =item *
9951:
9952: $namespace : the name of a .db file that contains the data needed or
9953: being set.
9954:
9955: =back
9956:
1.394 bowersj2 9957: =head1 OVERVIEW
1.191 harris41 9958:
1.394 bowersj2 9959: lonnet provides subroutines which interact with the
9960: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9961: about classes, users, and resources.
1.243 albertel 9962:
9963: For many of these objects you can also use this to store data about
9964: them or modify them in various ways.
1.191 harris41 9965:
1.394 bowersj2 9966: =head2 Symbs
1.191 harris41 9967:
1.394 bowersj2 9968: To identify a specific instance of a resource, LON-CAPA uses symbols
9969: or "symbs"X<symb>. These identifiers are built from the URL of the
9970: map, the resource number of the resource in the map, and the URL of
9971: the resource itself. The latter is somewhat redundant, but might help
9972: if maps change.
9973:
9974: An example is
9975:
9976: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9977:
9978: The respective map entry is
9979:
9980: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9981: title="Problem 2">
9982: </resource>
9983:
9984: Symbs are used by the random number generator, as well as to store and
9985: restore data specific to a certain instance of for example a problem.
9986:
9987: =head2 Storing And Retrieving Data
9988:
9989: X<store()>X<cstore()>X<restore()>Three of the most important functions
9990: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9991: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9992: is is the non-critical message twin of cstore. These functions are for
9993: handlers to store a perl hash to a user's permanent data space in an
9994: easy manner, and to retrieve it again on another call. It is expected
9995: that a handler would use this once at the beginning to retrieve data,
9996: and then again once at the end to send only the new data back.
9997:
9998: The data is stored in the user's data directory on the user's
9999: homeserver under the ID of the course.
10000:
10001: The hash that is returned by restore will have all of the previous
10002: value for all of the elements of the hash.
10003:
10004: Example:
10005:
10006: #creating a hash
10007: my %hash;
10008: $hash{'foo'}='bar';
10009:
10010: #storing it
10011: &Apache::lonnet::cstore(\%hash);
10012:
10013: #changing a value
10014: $hash{'foo'}='notbar';
10015:
10016: #adding a new value
10017: $hash{'bar'}='foo';
10018: &Apache::lonnet::cstore(\%hash);
10019:
10020: #retrieving the hash
10021: my %history=&Apache::lonnet::restore();
10022:
10023: #print the hash
10024: foreach my $key (sort(keys(%history))) {
10025: print("\%history{$key} = $history{$key}");
10026: }
10027:
10028: Will print out:
1.191 harris41 10029:
1.394 bowersj2 10030: %history{1:foo} = bar
10031: %history{1:keys} = foo:timestamp
10032: %history{1:timestamp} = 990455579
10033: %history{2:bar} = foo
10034: %history{2:foo} = notbar
10035: %history{2:keys} = foo:bar:timestamp
10036: %history{2:timestamp} = 990455580
10037: %history{bar} = foo
10038: %history{foo} = notbar
10039: %history{timestamp} = 990455580
10040: %history{version} = 2
10041:
10042: Note that the special hash entries C<keys>, C<version> and
10043: C<timestamp> were added to the hash. C<version> will be equal to the
10044: total number of versions of the data that have been stored. The
10045: C<timestamp> attribute will be the UNIX time the hash was
10046: stored. C<keys> is available in every historical section to list which
10047: keys were added or changed at a specific historical revision of a
10048: hash.
10049:
10050: B<Warning>: do not store the hash that restore returns directly. This
10051: will cause a mess since it will restore the historical keys as if the
10052: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10053:
1.394 bowersj2 10054: Calling convention:
1.191 harris41 10055:
1.394 bowersj2 10056: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10057: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10058:
1.394 bowersj2 10059: For more detailed information, see lonnet specific documentation.
1.191 harris41 10060:
1.394 bowersj2 10061: =head1 RETURN MESSAGES
1.191 harris41 10062:
1.394 bowersj2 10063: =over 4
1.191 harris41 10064:
1.394 bowersj2 10065: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10066:
1.394 bowersj2 10067: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10068: when the connection is brought back up
1.191 harris41 10069:
1.394 bowersj2 10070: =item * B<con_failed>: unable to contact remote host and unable to save message
10071: for later delivery
1.191 harris41 10072:
1.967 bisitz 10073: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10074:
1.394 bowersj2 10075: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10076: that was requested
1.191 harris41 10077:
1.243 albertel 10078: =back
1.191 harris41 10079:
1.243 albertel 10080: =head1 PUBLIC SUBROUTINES
1.191 harris41 10081:
1.243 albertel 10082: =head2 Session Environment Functions
1.191 harris41 10083:
1.243 albertel 10084: =over 4
1.191 harris41 10085:
1.394 bowersj2 10086: =item *
10087: X<appenv()>
1.949 raeburn 10088: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10089: the user envirnoment file, and will be restored for each access this
1.620 albertel 10090: user makes during this session, also modifies the %env for the current
1.949 raeburn 10091: process. Optional rolesarrayref - if defined contains a reference to an array
10092: of roles which are exempt from the restriction on modifying user.role entries
10093: in the user's environment.db and in %env.
1.191 harris41 10094:
10095: =item *
1.394 bowersj2 10096: X<delenv()>
1.987 raeburn 10097: B<delenv($delthis,$regexp)>: removes all items from the session
10098: environment file that begin with $delthis. If the
10099: optional second arg - $regexp - is true, $delthis is treated as a
10100: regular expression, otherwise \Q$delthis\E is used.
10101: The values are also deleted from the current processes %env.
1.191 harris41 10102:
1.795 albertel 10103: =item * get_env_multiple($name)
10104:
10105: gets $name from the %env hash, it seemlessly handles the cases where multiple
10106: values may be defined and end up as an array ref.
10107:
10108: returns an array of values
10109:
1.243 albertel 10110: =back
10111:
10112: =head2 User Information
1.191 harris41 10113:
1.243 albertel 10114: =over 4
1.191 harris41 10115:
10116: =item *
1.394 bowersj2 10117: X<queryauthenticate()>
10118: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10119: authentication scheme
10120:
10121: =item *
1.394 bowersj2 10122: X<authenticate()>
10123: B<authenticate($uname,$upass,$udom)>: try to
10124: authenticate user from domain's lib servers (first use the current
10125: one). C<$upass> should be the users password.
1.191 harris41 10126:
10127: =item *
1.394 bowersj2 10128: X<homeserver()>
10129: B<homeserver($uname,$udom)>: find the server which has
10130: the user's directory and files (there must be only one), this caches
10131: the answer, and also caches if there is a borken connection.
1.191 harris41 10132:
10133: =item *
1.394 bowersj2 10134: X<idget()>
10135: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10136: (IDs are a unique resource in a domain, there must be only 1 ID per
10137: username, and only 1 username per ID in a specific domain) (returns
10138: hash: id=>name,id=>name)
1.191 harris41 10139:
10140: =item *
1.394 bowersj2 10141: X<idrget()>
10142: B<idrget($udom,@unames)>: find the IDs behind a list of
10143: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10144:
10145: =item *
1.394 bowersj2 10146: X<idput()>
10147: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10148:
10149: =item *
1.394 bowersj2 10150: X<rolesinit()>
10151: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10152:
10153: =item *
1.551 albertel 10154: X<getsection()>
10155: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10156: course $cname, return section name/number or '' for "not in course"
10157: and '-1' for "no section"
10158:
10159: =item *
1.394 bowersj2 10160: X<userenvironment()>
10161: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10162: passed in @what from the requested user's environment, returns a hash
10163:
1.858 raeburn 10164: =item *
10165: X<userlog_query()>
1.859 albertel 10166: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10167: activity.log file. %filters defines filters applied when parsing the
10168: log file. These can be start or end timestamps, or the type of action
10169: - log to look for Login or Logout events, check for Checkin or
10170: Checkout, role for role selection. The response is in the form
10171: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10172: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10173:
1.243 albertel 10174: =back
10175:
10176: =head2 User Roles
10177:
10178: =over 4
10179:
10180: =item *
10181:
1.810 raeburn 10182: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10183: F: full access
10184: U,I,K: authentication modes (cxx only)
10185: '': forbidden
10186: 1: user needs to choose course
10187: 2: browse allowed
1.766 albertel 10188: A: passphrase authentication needed
1.243 albertel 10189:
10190: =item *
10191:
10192: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10193: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10194: and course level
10195:
10196: =item *
10197:
1.988 raeburn 10198: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10199: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10200: $type is Course (default) or Community.
1.988 raeburn 10201: If $forcedefault evaluates to true, text returned will be default
10202: text for $type. Otherwise, if this is a course, the text returned
10203: will be a custom name for the role (if defined in the course's
10204: environment). If no custom name is defined the default is returned.
10205:
1.832 raeburn 10206: =item *
10207:
1.935 raeburn 10208: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10209: All arguments are optional. Returns a hash of a roles, either for
10210: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10211: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10212: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10213: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10214: For each key, value is set to colon-separated start and end times for
10215: the role. If no username and domain are specified, will default to
1.934 raeburn 10216: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10217: of role statuses (active, future or previous), roles
10218: (e.g., cc,in, st etc.) and domains of the roles which can be used
10219: to restrict the list of roles reported. If no array ref is
10220: provided for types, will default to return only active roles.
1.834 albertel 10221:
1.243 albertel 10222: =back
10223:
10224: =head2 User Modification
10225:
10226: =over 4
10227:
10228: =item *
10229:
1.957 raeburn 10230: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10231: user for the level given by URL. Optional start and end dates (leave empty
10232: string or zero for "no date")
1.191 harris41 10233:
10234: =item *
10235:
1.243 albertel 10236: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10237: change a users, password, possible return values are: ok,
10238: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10239: refused
1.191 harris41 10240:
10241: =item *
10242:
1.243 albertel 10243: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10244:
10245: =item *
10246:
1.1058 raeburn 10247: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10248: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10249:
10250: will update user information (firstname,middlename,lastname,generation,
10251: permanentemail), and if forceid is true, student/employee ID also.
10252: A user's institutional affiliation(s) can also be updated.
10253: User information fields will not be overwritten with empty entries
10254: unless the field is included in the $candelete array reference.
10255: This array is included when a single user is modified via "Manage Users",
10256: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10257:
10258: =item *
10259:
1.286 matthew 10260: modifystudent
10261:
1.957 raeburn 10262: modify a student's enrollment and identification information.
1.286 matthew 10263: The course id is resolved based on the current users environment.
10264: This means the envoking user must be a course coordinator or otherwise
10265: associated with a course.
10266:
1.297 matthew 10267: This call is essentially a wrapper for lonnet::modifyuser and
10268: lonnet::modify_student_enrollment
1.286 matthew 10269:
10270: Inputs:
10271:
10272: =over 4
10273:
1.957 raeburn 10274: =item B<$udom> Student's loncapa domain
1.286 matthew 10275:
1.957 raeburn 10276: =item B<$uname> Student's loncapa login name
1.286 matthew 10277:
1.964 bisitz 10278: =item B<$uid> Student/Employee ID
1.286 matthew 10279:
1.957 raeburn 10280: =item B<$umode> Student's authentication mode
1.286 matthew 10281:
1.957 raeburn 10282: =item B<$upass> Student's password
1.286 matthew 10283:
1.957 raeburn 10284: =item B<$first> Student's first name
1.286 matthew 10285:
1.957 raeburn 10286: =item B<$middle> Student's middle name
1.286 matthew 10287:
1.957 raeburn 10288: =item B<$last> Student's last name
1.286 matthew 10289:
1.957 raeburn 10290: =item B<$gene> Student's generation
1.286 matthew 10291:
1.957 raeburn 10292: =item B<$usec> Student's section in course
1.286 matthew 10293:
10294: =item B<$end> Unix time of the roles expiration
10295:
10296: =item B<$start> Unix time of the roles start date
10297:
10298: =item B<$forceid> If defined, allow $uid to be changed
10299:
10300: =item B<$desiredhome> server to use as home server for student
10301:
1.957 raeburn 10302: =item B<$email> Student's permanent e-mail address
10303:
10304: =item B<$type> Type of enrollment (auto or manual)
10305:
1.963 raeburn 10306: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10307:
10308: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10309:
1.963 raeburn 10310: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10311:
1.963 raeburn 10312: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10313:
1.963 raeburn 10314: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10315:
1.286 matthew 10316: =back
1.297 matthew 10317:
10318: =item *
10319:
10320: modify_student_enrollment
10321:
10322: Change a students enrollment status in a class. The environment variable
10323: 'role.request.course' must be defined for this function to proceed.
10324:
10325: Inputs:
10326:
10327: =over 4
10328:
10329: =item $udom, students domain
10330:
10331: =item $uname, students name
10332:
10333: =item $uid, students user id
10334:
10335: =item $first, students first name
10336:
10337: =item $middle
10338:
10339: =item $last
10340:
10341: =item $gene
10342:
10343: =item $usec
10344:
10345: =item $end
10346:
10347: =item $start
10348:
1.957 raeburn 10349: =item $type
10350:
10351: =item $locktype
10352:
10353: =item $cid
10354:
10355: =item $selfenroll
10356:
10357: =item $context
10358:
1.297 matthew 10359: =back
10360:
1.191 harris41 10361:
10362: =item *
10363:
1.243 albertel 10364: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10365: custom role; give a custom role to a user for the level given by URL. Specify
10366: name and domain of role author, and role name
1.191 harris41 10367:
10368: =item *
10369:
1.243 albertel 10370: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10371:
10372: =item *
10373:
1.243 albertel 10374: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10375:
10376: =back
10377:
10378: =head2 Course Infomation
10379:
10380: =over 4
1.191 harris41 10381:
10382: =item *
10383:
1.631 albertel 10384: coursedescription($courseid) : returns a hash of information about the
10385: specified course id, including all environment settings for the
10386: course, the description of the course will be in the hash under the
10387: key 'description'
1.191 harris41 10388:
10389: =item *
10390:
1.624 albertel 10391: resdata($name,$domain,$type,@which) : request for current parameter
10392: setting for a specific $type, where $type is either 'course' or 'user',
10393: @what should be a list of parameters to ask about. This routine caches
10394: answers for 5 minutes.
1.243 albertel 10395:
1.877 foxr 10396: =item *
10397:
10398: get_courseresdata($courseid, $domain) : dump the entire course resource
10399: data base, returning a hash that is keyed by the resource name and has
10400: values that are the resource value. I believe that the timestamps and
10401: versions are also returned.
10402:
10403:
1.243 albertel 10404: =back
10405:
10406: =head2 Course Modification
10407:
10408: =over 4
1.191 harris41 10409:
10410: =item *
10411:
1.243 albertel 10412: writecoursepref($courseid,%prefs) : write preferences (environment
10413: database) for a course
1.191 harris41 10414:
10415: =item *
10416:
1.1011 raeburn 10417: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10418:
10419: =item *
10420:
1.1038 raeburn 10421: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10422:
10423: =back
10424:
10425: =head2 Resource Subroutines
10426:
10427: =over 4
1.191 harris41 10428:
10429: =item *
10430:
1.243 albertel 10431: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10432:
10433: =item *
10434:
1.243 albertel 10435: repcopy($filename) : subscribes to the requested file, and attempts to
10436: replicate from the owning library server, Might return
1.607 raeburn 10437: 'unavailable', 'not_found', 'forbidden', 'ok', or
10438: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10439: resource. Expects the local filesystem pathname
10440: (/home/httpd/html/res/....)
10441:
10442: =back
10443:
10444: =head2 Resource Information
10445:
10446: =over 4
1.191 harris41 10447:
10448: =item *
10449:
1.243 albertel 10450: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10451: a vairety of different possible values, $varname should be a request
10452: string, and the other parameters can be used to specify who and what
10453: one is asking about.
10454:
10455: Possible values for $varname are environment.lastname (or other item
10456: from the envirnment hash), user.name (or someother aspect about the
10457: user), resource.0.maxtries (or some other part and parameter of a
10458: resource)
1.204 albertel 10459:
10460: =item *
10461:
1.243 albertel 10462: directcondval($number) : get current value of a condition; reads from a state
10463: string
1.204 albertel 10464:
10465: =item *
10466:
1.243 albertel 10467: condval($condidx) : value of condition index based on state
1.204 albertel 10468:
10469: =item *
10470:
1.243 albertel 10471: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10472: resource's metadata, $what should be either a specific key, or either
10473: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10474: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10475:
10476: this function automatically caches all requests
1.191 harris41 10477:
10478: =item *
10479:
1.243 albertel 10480: metadata_query($query,$custom,$customshow) : make a metadata query against the
10481: network of library servers; returns file handle of where SQL and regex results
10482: will be stored for query
1.191 harris41 10483:
10484: =item *
10485:
1.243 albertel 10486: symbread($filename) : return symbolic list entry (filename argument optional);
10487: returns the data handle
1.191 harris41 10488:
10489: =item *
10490:
1.243 albertel 10491: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10492: a possible symb for the URL in $thisfn, and if is an encryypted
10493: resource that the user accessed using /enc/ returns a 1 on success, 0
10494: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10495: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10496:
1.191 harris41 10497:
10498: =item *
10499:
1.243 albertel 10500: symbclean($symb) : removes versions numbers from a symb, returns the
10501: cleaned symb
1.191 harris41 10502:
10503: =item *
10504:
1.243 albertel 10505: is_on_map($uri) : checks if the $uri is somewhere on the current
10506: course map, user must be in a course for it to work.
1.191 harris41 10507:
10508: =item *
10509:
1.243 albertel 10510: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10511:
10512: =item *
10513:
1.243 albertel 10514: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10515: a random seed, all arguments are optional, if they aren't sent it uses the
10516: environment to derive them. Note: if symb isn't sent and it can't get one
10517: from &symbread it will use the current time as its return value
1.191 harris41 10518:
10519: =item *
10520:
1.243 albertel 10521: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10522: unfakeable, receipt
1.191 harris41 10523:
10524: =item *
10525:
1.620 albertel 10526: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10527:
10528: =item *
10529:
1.243 albertel 10530: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10531:
10532: =item *
10533:
1.243 albertel 10534: 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 10535:
10536: =item *
10537:
1.243 albertel 10538: 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 10539:
10540: =item *
10541:
1.243 albertel 10542: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10543:
10544: =item *
10545:
1.243 albertel 10546: devalidate($symb) : devalidate temporary spreadsheet calculations,
10547: forcing spreadsheet to reevaluate the resource scores next time.
10548:
10549: =back
10550:
10551: =head2 Storing/Retreiving Data
10552:
10553: =over 4
1.191 harris41 10554:
10555: =item *
10556:
1.243 albertel 10557: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10558: for this url; hashref needs to be given and should be a \%hashname; the
10559: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10560: be derived from the env
1.191 harris41 10561:
10562: =item *
10563:
1.243 albertel 10564: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10565: uses critical subroutine
1.191 harris41 10566:
10567: =item *
10568:
1.243 albertel 10569: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10570: all args are optional
1.191 harris41 10571:
10572: =item *
10573:
1.717 albertel 10574: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10575: dumps the complete (or key matching regexp) namespace into a hash
10576: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10577: normally &store()ed into
10578:
10579: $range should be either an integer '100' (give me the first 100
10580: matching records)
10581: or be two integers sperated by a - with no spaces
10582: '30-50' (give me the 30th through the 50th matching
10583: records)
10584:
10585:
10586: =item *
10587:
10588: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10589: replaces a &store() version of data with a replacement set of data
10590: for a particular resource in a namespace passed in the $storehash hash
10591: reference
10592:
10593: =item *
10594:
1.243 albertel 10595: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10596: works very similar to store/cstore, but all data is stored in a
10597: temporary location and can be reset using tmpreset, $storehash should
10598: be a hash reference, returns nothing on success
1.191 harris41 10599:
10600: =item *
10601:
1.243 albertel 10602: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10603: similar to restore, but all data is stored in a temporary location and
10604: can be reset using tmpreset. Returns a hash of values on success,
10605: error string otherwise.
1.191 harris41 10606:
10607: =item *
10608:
1.243 albertel 10609: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10610: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10611:
10612: =item *
10613:
1.243 albertel 10614: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10615: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10616:
10617: =item *
10618:
1.243 albertel 10619: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10620: namesp ($udom and $uname are optional)
1.191 harris41 10621:
10622: =item *
10623:
1.702 albertel 10624: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10625: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10626: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10627:
1.702 albertel 10628: $range should be either an integer '100' (give me the first 100
10629: matching records)
10630: or be two integers sperated by a - with no spaces
10631: '30-50' (give me the 30th through the 50th matching
10632: records)
1.449 matthew 10633: =item *
10634:
10635: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10636: $store can be a scalar, an array reference, or if the amount to be
10637: incremented is > 1, a hash reference.
10638:
10639: ($udom and $uname are optional)
1.191 harris41 10640:
10641: =item *
10642:
1.243 albertel 10643: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10644: ($udom and $uname are optional)
1.191 harris41 10645:
10646: =item *
10647:
1.243 albertel 10648: cput($namespace,$storehash,$udom,$uname) : critical put
10649: ($udom and $uname are optional)
1.191 harris41 10650:
10651: =item *
10652:
1.748 albertel 10653: newput($namespace,$storehash,$udom,$uname) :
10654:
10655: Attempts to store the items in the $storehash, but only if they don't
10656: currently exist, if this succeeds you can be certain that you have
10657: successfully created a new key value pair in the $namespace db.
10658:
10659:
10660: Args:
10661: $namespace: name of database to store values to
10662: $storehash: hashref to store to the db
10663: $udom: (optional) domain of user containing the db
10664: $uname: (optional) name of user caontaining the db
10665:
10666: Returns:
10667: 'ok' -> succeeded in storing all keys of $storehash
10668: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10669: least <key> already existed in the db (other
10670: requested keys may also already exist)
1.967 bisitz 10671: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10672: 'con_lost' -> unable to contact request server
10673: 'refused' -> action was not allowed by remote machine
10674:
10675:
10676: =item *
10677:
1.243 albertel 10678: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10679: reference filled in from namesp (encrypts the return communication)
10680: ($udom and $uname are optional)
1.191 harris41 10681:
10682: =item *
10683:
1.243 albertel 10684: log($udom,$name,$home,$message) : write to permanent log for user; use
10685: critical subroutine
10686:
1.806 raeburn 10687: =item *
10688:
1.860 raeburn 10689: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10690: array reference filled in from namespace found in domain level on either
10691: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10692:
10693: =item *
10694:
1.860 raeburn 10695: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10696: domain level either on specified domain server ($uhome) or primary domain
10697: server ($udom and $uhome are optional)
1.806 raeburn 10698:
1.943 raeburn 10699: =item *
10700:
10701: get_domain_defaults($target_domain) : returns hash with defaults for
10702: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10703: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10704: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10705: Values are retrieved from cache (if current), or from domain's configuration.db
10706: (if available), or lastly from values in lonTabs/dns_domain,tab,
10707: or lonTabs/domain.tab.
10708:
10709: %domdefaults = &get_auth_defaults($target_domain);
10710:
1.243 albertel 10711: =back
10712:
10713: =head2 Network Status Functions
10714:
10715: =over 4
1.191 harris41 10716:
10717: =item *
10718:
10719: dirlist($uri) : return directory list based on URI
10720:
10721: =item *
10722:
1.243 albertel 10723: spareserver() : find server with least workload from spare.tab
10724:
1.986 foxr 10725:
10726: =item *
10727:
10728: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10729: if there is no corresponding loncapa host.
10730:
1.243 albertel 10731: =back
10732:
1.986 foxr 10733:
1.243 albertel 10734: =head2 Apache Request
10735:
10736: =over 4
1.191 harris41 10737:
10738: =item *
10739:
1.243 albertel 10740: ssi($url,%hash) : server side include, does a complete request cycle on url to
10741: localhost, posts hash
10742:
10743: =back
10744:
10745: =head2 Data to String to Data
10746:
10747: =over 4
1.191 harris41 10748:
10749: =item *
10750:
1.243 albertel 10751: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10752: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10753:
10754: =item *
10755:
1.243 albertel 10756: hashref2str($hashref) : convert a hashref into a string complete with
10757: escaping and '=' and '&' separators, supports elements that are
10758: arrayrefs and hashrefs
1.191 harris41 10759:
10760: =item *
10761:
1.243 albertel 10762: arrayref2str($arrayref) : convert an arrayref into a string complete
10763: with escaping and '&' separators, supports elements that are arrayrefs
10764: and hashrefs
1.191 harris41 10765:
10766: =item *
10767:
1.243 albertel 10768: str2hash($string) : convert string to hash using unescaping and
10769: splitting on '=' and '&', supports elements that are arrayrefs and
10770: hashrefs
1.191 harris41 10771:
10772: =item *
10773:
1.243 albertel 10774: str2array($string) : convert string to hash using unescaping and
10775: splitting on '&', supports elements that are arrayrefs and hashrefs
10776:
10777: =back
10778:
10779: =head2 Logging Routines
10780:
10781: =over 4
10782:
10783: These routines allow one to make log messages in the lonnet.log and
10784: lonnet.perm logfiles.
1.191 harris41 10785:
10786: =item *
10787:
1.243 albertel 10788: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10789:
10790: =item *
10791:
1.243 albertel 10792: logthis() : append message to the normal lonnet.log file, it gets
10793: preiodically rolled over and deleted.
1.191 harris41 10794:
10795: =item *
10796:
1.243 albertel 10797: logperm() : append a permanent message to lonnet.perm.log, this log
10798: file never gets deleted by any automated portion of the system, only
10799: messages of critical importance should go in here.
10800:
10801: =back
10802:
10803: =head2 General File Helper Routines
10804:
10805: =over 4
1.191 harris41 10806:
10807: =item *
10808:
1.481 raeburn 10809: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10810: (a) files in /uploaded
10811: (i) If a local copy of the file exists -
10812: compares modification date of local copy with last-modified date for
10813: definitive version stored on home server for course. If local copy is
10814: stale, requests a new version from the home server and stores it.
10815: If the original has been removed from the home server, then local copy
10816: is unlinked.
10817: (ii) If local copy does not exist -
10818: requests the file from the home server and stores it.
10819:
10820: If $caller is 'uploadrep':
10821: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10822: for request for files originally uploaded via DOCS.
10823: - returns 'ok' if fresh local copy now available, -1 otherwise.
10824:
10825: Otherwise:
10826: This indicates a call from the content generation phase of the request.
10827: - returns the entire contents of the file or -1.
10828:
10829: (b) files in /res
10830: - returns the entire contents of a file or -1;
10831: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10832:
1.712 albertel 10833:
10834: =item *
10835:
10836: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10837: reference
10838:
10839: returns either a stat() list of data about the file or an empty list
10840: if the file doesn't exist or couldn't find out about it (connection
10841: problems or user unknown)
10842:
1.191 harris41 10843: =item *
10844:
1.243 albertel 10845: filelocation($dir,$file) : returns file system location of a file
10846: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10847: directory that relative $file lookups are to looked in ($dir of /a/dir
10848: and a file of ../bob will become /a/bob)
1.191 harris41 10849:
10850: =item *
10851:
10852: hreflocation($dir,$file) : returns file system location or a URL; same as
10853: filelocation except for hrefs
10854:
10855: =item *
10856:
10857: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10858:
1.243 albertel 10859: =back
10860:
1.608 albertel 10861: =head2 Usererfile file routines (/uploaded*)
10862:
10863: =over 4
10864:
10865: =item *
10866:
10867: userfileupload(): main rotine for putting a file in a user or course's
10868: filespace, arguments are,
10869:
1.620 albertel 10870: formname - required - this is the name of the element in $env where the
1.608 albertel 10871: filename, and the contents of the file to create/modifed exist
1.620 albertel 10872: the filename is in $env{'form.'.$formname.'.filename'} and the
10873: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10874: coursedoc - if true, store the file in the course of the active role
10875: of the current user
10876: subdir - required - subdirectory to put the file in under ../userfiles/
10877: if undefined, it will be placed in "unknown"
10878:
10879: (This routine calls clean_filename() to remove any dangerous
10880: characters from the filename, and then calls finuserfileupload() to
10881: complete the transaction)
10882:
10883: returns either the url of the uploaded file (/uploaded/....) if successful
10884: and /adm/notfound.html if unsuccessful
10885:
10886: =item *
10887:
10888: clean_filename(): routine for cleaing a filename up for storage in
10889: userfile space, argument is:
10890:
10891: filename - proposed filename
10892:
10893: returns: the new clean filename
10894:
10895: =item *
10896:
10897: finishuserfileupload(): routine that creaes and sends the file to
10898: userspace, probably shouldn't be called directly
10899:
10900: docuname: username or courseid of destination for the file
10901: docudom: domain of user/course of destination for the file
10902: formname: same as for userfileupload()
10903: fname: filename (inculding subdirectories) for the file
10904:
10905: returns either the url of the uploaded file (/uploaded/....) if successful
10906: and /adm/notfound.html if unsuccessful
10907:
10908: =item *
10909:
10910: renameuserfile(): renames an existing userfile to a new name
10911:
10912: Args:
10913: docuname: username or courseid of destination for the file
10914: docudom: domain of user/course of destination for the file
10915: old: current file name (including any subdirs under userfiles)
10916: new: desired file name (including any subdirs under userfiles)
10917:
10918: =item *
10919:
10920: mkdiruserfile(): creates a directory is a userfiles dir
10921:
10922: Args:
10923: docuname: username or courseid of destination for the file
10924: docudom: domain of user/course of destination for the file
10925: dir: dir to create (including any subdirs under userfiles)
10926:
10927: =item *
10928:
10929: removeuserfile(): removes a file that exists in userfiles
10930:
10931: Args:
10932: docuname: username or courseid of destination for the file
10933: docudom: domain of user/course of destination for the file
10934: fname: filname to delete (including any subdirs under userfiles)
10935:
10936: =item *
10937:
10938: removeuploadedurl(): convience function for removeuserfile()
10939:
10940: Args:
10941: url: a full /uploaded/... url to delete
10942:
1.747 albertel 10943: =item *
10944:
10945: get_portfile_permissions():
10946: Args:
10947: domain: domain of user or course contain the portfolio files
10948: user: name of user or num of course contain the portfolio files
10949: Returns:
10950: hashref of a dump of the proper file_permissions.db
10951:
10952:
10953: =item *
10954:
10955: get_access_controls():
10956:
10957: Args:
10958: current_permissions: the hash ref returned from get_portfile_permissions()
10959: group: (optional) the group you want the files associated with
10960: file: (optional) the file you want access info on
10961:
10962: Returns:
1.749 raeburn 10963: a hash (keys are file names) of hashes containing
10964: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10965: values are XML containing access control settings (see below)
1.747 albertel 10966:
10967: Internal notes:
10968:
1.749 raeburn 10969: access controls are stored in file_permissions.db as key=value pairs.
10970: key -> path to file/file_name\0uniqueID:scope_end_start
10971: where scope -> public,guest,course,group,domains or users.
10972: end -> UNIX time for end of access (0 -> no end date)
10973: start -> UNIX time for start of access
10974:
10975: value -> XML description of access control
10976: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10977: <start></start>
10978: <end></end>
10979:
10980: <password></password> for scope type = guest
10981:
10982: <domain></domain> for scope type = course or group
10983: <number></number>
10984: <roles id="">
10985: <role></role>
10986: <access></access>
10987: <section></section>
10988: <group></group>
10989: </roles>
10990:
10991: <dom></dom> for scope type = domains
10992:
10993: <users> for scope type = users
10994: <user>
10995: <uname></uname>
10996: <udom></udom>
10997: </user>
10998: </users>
10999: </scope>
11000:
11001: Access data is also aggregated for each file in an additional key=value pair:
11002: key -> path to file/file_name\0accesscontrol
11003: value -> reference to hash
11004: hash contains key = value pairs
11005: where key = uniqueID:scope_end_start
11006: value = UNIX time record was last updated
11007:
11008: Used to improve speed of look-ups of access controls for each file.
11009:
11010: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11011:
11012: modify_access_controls():
11013:
11014: Modifies access controls for a portfolio file
11015: Args
11016: 1. file name
11017: 2. reference to hash of required changes,
11018: 3. domain
11019: 4. username
11020: where domain,username are the domain of the portfolio owner
11021: (either a user or a course)
11022:
11023: Returns:
11024: 1. result of additions or updates ('ok' or 'error', with error message).
11025: 2. result of deletions ('ok' or 'error', with error message).
11026: 3. reference to hash of any new or updated access controls.
11027: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11028: key = integer (inbound ID)
11029: value = uniqueID
1.747 albertel 11030:
1.608 albertel 11031: =back
11032:
1.243 albertel 11033: =head2 HTTP Helper Routines
11034:
11035: =over 4
11036:
1.191 harris41 11037: =item *
11038:
11039: escape() : unpack non-word characters into CGI-compatible hex codes
11040:
11041: =item *
11042:
11043: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11044:
1.243 albertel 11045: =back
11046:
11047: =head1 PRIVATE SUBROUTINES
11048:
11049: =head2 Underlying communication routines (Shouldn't call)
11050:
11051: =over 4
11052:
11053: =item *
11054:
11055: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11056:
11057: =item *
11058:
11059: reply() : uses subreply to send a message to remote machine, logs all failures
11060:
11061: =item *
11062:
11063: critical() : passes a critical message to another server; if cannot
11064: get through then place message in connection buffer directory and
11065: returns con_delayed, if incapable of saving message, returns
11066: con_failed
11067:
11068: =item *
11069:
11070: reconlonc() : tries to reconnect lonc client processes.
11071:
11072: =back
11073:
11074: =head2 Resource Access Logging
11075:
11076: =over 4
11077:
11078: =item *
11079:
11080: flushcourselogs() : flush (save) buffer logs and access logs
11081:
11082: =item *
11083:
11084: courselog($what) : save message for course in hash
11085:
11086: =item *
11087:
11088: courseacclog($what) : save message for course using &courselog(). Perform
11089: special processing for specific resource types (problems, exams, quizzes, etc).
11090:
1.191 harris41 11091: =item *
11092:
11093: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11094: as a PerlChildExitHandler
1.243 albertel 11095:
11096: =back
11097:
11098: =head2 Other
11099:
11100: =over 4
11101:
11102: =item *
11103:
11104: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11105:
11106: =back
11107:
11108: =cut
1.877 foxr 11109:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>