Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1063
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1063 ! raeburn 4: # $Id: lonnet.pm,v 1.1062 2010/05/04 15:21:29 droeschl 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'});
1.1063 ! raeburn 3996: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},1);
1.1002 raeburn 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.1062 droeschl 5455: #SD remove this
5456: &logthis("Querying server:$server");
1.118 harris41 5457: unless ($custom or $customshow) {
5458: my $reply=&reply("querysend:".&escape($query),$server);
5459: $rhash{$server}=$reply;
5460: }
5461: else {
5462: my $reply=&reply("querysend:".&escape($query).':'.
5463: &escape($custom).':'.&escape($customshow),
5464: $server);
5465: $rhash{$server}=$reply;
5466: }
1.112 harris41 5467: }
1.118 harris41 5468: return \%rhash;
1.240 www 5469: }
5470:
5471: # ----------------------------------------- Send log queries and wait for reply
5472:
5473: sub log_query {
5474: my ($uname,$udom,$query,%filters)=@_;
5475: my $uhome=&homeserver($uname,$udom);
5476: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5477: my $uhost=&hostname($uhome);
1.800 albertel 5478: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5479: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5480: $uhome);
1.479 albertel 5481: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5482: return get_query_reply($queryid);
5483: }
5484:
1.818 raeburn 5485: # -------------------------- Update MySQL table for portfolio file
5486:
5487: sub update_portfolio_table {
1.821 raeburn 5488: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5489: if ($group ne '') {
5490: $file_name =~s /^\Q$group\E//;
5491: }
1.818 raeburn 5492: my $homeserver = &homeserver($uname,$udom);
5493: my $queryid=
1.821 raeburn 5494: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5495: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5496: my $reply = &get_query_reply($queryid);
5497: return $reply;
5498: }
5499:
1.899 raeburn 5500: # -------------------------- Update MySQL allusers table
5501:
5502: sub update_allusers_table {
5503: my ($uname,$udom,$names) = @_;
5504: my $homeserver = &homeserver($uname,$udom);
5505: my $queryid=
5506: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5507: 'lastname='.&escape($names->{'lastname'}).'%%'.
5508: 'firstname='.&escape($names->{'firstname'}).'%%'.
5509: 'middlename='.&escape($names->{'middlename'}).'%%'.
5510: 'generation='.&escape($names->{'generation'}).'%%'.
5511: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5512: 'id='.&escape($names->{'id'}),$homeserver);
5513: my $reply = &get_query_reply($queryid);
5514: return $reply;
5515: }
5516:
1.508 raeburn 5517: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5518:
5519: sub fetch_enrollment_query {
1.511 raeburn 5520: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5521: my $homeserver;
1.547 raeburn 5522: my $maxtries = 1;
1.508 raeburn 5523: if ($context eq 'automated') {
5524: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5525: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5526: } else {
5527: $homeserver = &homeserver($cnum,$dom);
5528: }
1.838 albertel 5529: my $host=&hostname($homeserver);
1.506 raeburn 5530: my $cmd = '';
1.1000 raeburn 5531: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5532: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5533: }
5534: $cmd =~ s/%%$//;
5535: $cmd = &escape($cmd);
5536: my $query = 'fetchenrollment';
1.620 albertel 5537: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5538: unless ($queryid=~/^\Q$host\E\_/) {
5539: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5540: return 'error: '.$queryid;
5541: }
1.506 raeburn 5542: my $reply = &get_query_reply($queryid);
1.547 raeburn 5543: my $tries = 1;
5544: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5545: $reply = &get_query_reply($queryid);
5546: $tries ++;
5547: }
1.526 raeburn 5548: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5549: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5550: } else {
1.901 albertel 5551: my @responses = split(/:/,$reply);
1.515 raeburn 5552: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5553: foreach my $line (@responses) {
5554: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5555: $$replyref{$key} = $value;
5556: }
5557: } else {
1.506 raeburn 5558: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5559: foreach my $line (@responses) {
5560: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5561: $$replyref{$key} = $value;
5562: if ($value > 0) {
1.800 albertel 5563: foreach my $item (@{$$affiliatesref{$key}}) {
5564: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5565: my $destname = $pathname.'/'.$filename;
5566: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5567: if ($xml_classlist =~ /^error/) {
5568: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5569: } else {
1.506 raeburn 5570: if ( open(FILE,">$destname") ) {
5571: print FILE &unescape($xml_classlist);
5572: close(FILE);
1.526 raeburn 5573: } else {
5574: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5575: }
5576: }
5577: }
5578: }
5579: }
5580: }
5581: return 'ok';
5582: }
5583: return 'error';
5584: }
5585:
1.242 www 5586: sub get_query_reply {
5587: my $queryid=shift;
1.240 www 5588: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5589: my $reply='';
5590: for (1..100) {
5591: sleep 2;
5592: if (-e $replyfile.'.end') {
1.448 albertel 5593: if (open(my $fh,$replyfile)) {
1.904 albertel 5594: $reply = join('',<$fh>);
5595: close($fh);
1.240 www 5596: } else { return 'error: reply_file_error'; }
1.242 www 5597: return &unescape($reply);
5598: }
1.240 www 5599: }
1.242 www 5600: return 'timeout:'.$queryid;
1.240 www 5601: }
5602:
5603: sub courselog_query {
1.241 www 5604: #
5605: # possible filters:
5606: # url: url or symb
5607: # username
5608: # domain
5609: # action: view, submit, grade
5610: # start: timestamp
5611: # end: timestamp
5612: #
1.240 www 5613: my (%filters)=@_;
1.620 albertel 5614: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5615: if ($filters{'url'}) {
5616: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5617: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5618: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5619: }
1.620 albertel 5620: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5621: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5622: return &log_query($cname,$cdom,'courselog',%filters);
5623: }
5624:
5625: sub userlog_query {
1.858 raeburn 5626: #
5627: # possible filters:
5628: # action: log check role
5629: # start: timestamp
5630: # end: timestamp
5631: #
1.240 www 5632: my ($uname,$udom,%filters)=@_;
5633: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5634: }
5635:
1.506 raeburn 5636: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5637:
5638: sub auto_run {
1.508 raeburn 5639: my ($cnum,$cdom) = @_;
1.876 raeburn 5640: my $response = 0;
5641: my $settings;
5642: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5643: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5644: $settings = $domconfig{'autoenroll'};
5645: if ($settings->{'run'} eq '1') {
5646: $response = 1;
5647: }
5648: } else {
1.934 raeburn 5649: my $homeserver;
5650: if (&is_course($cdom,$cnum)) {
5651: $homeserver = &homeserver($cnum,$cdom);
5652: } else {
5653: $homeserver = &domain($cdom,'primary');
5654: }
5655: if ($homeserver ne 'no_host') {
5656: $response = &reply('autorun:'.$cdom,$homeserver);
5657: }
1.876 raeburn 5658: }
1.506 raeburn 5659: return $response;
5660: }
1.776 albertel 5661:
1.506 raeburn 5662: sub auto_get_sections {
1.508 raeburn 5663: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5664: my $homeserver;
5665: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5666: $homeserver = &homeserver($cnum,$cdom);
5667: }
5668: if (!defined($homeserver)) {
5669: if ($cdom =~ /^$match_domain$/) {
5670: $homeserver = &domain($cdom,'primary');
5671: }
5672: }
5673: my @secs;
5674: if (defined($homeserver)) {
5675: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5676: unless ($response eq 'refused') {
5677: @secs = split(/:/,$response);
5678: }
1.506 raeburn 5679: }
5680: return @secs;
5681: }
1.776 albertel 5682:
1.506 raeburn 5683: sub auto_new_course {
1.508 raeburn 5684: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5685: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5686: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5687: return $response;
5688: }
1.776 albertel 5689:
1.506 raeburn 5690: sub auto_validate_courseID {
1.508 raeburn 5691: my ($cnum,$cdom,$inst_course_id) = @_;
5692: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5693: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5694: return $response;
5695: }
1.776 albertel 5696:
1.1007 raeburn 5697: sub auto_validate_instcode {
1.1020 raeburn 5698: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5699: my ($homeserver,$response);
5700: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5701: $homeserver = &homeserver($cnum,$cdom);
5702: }
5703: if (!defined($homeserver)) {
5704: if ($cdom =~ /^$match_domain$/) {
5705: $homeserver = &domain($cdom,'primary');
5706: }
5707: }
5708: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020 raeburn 5709: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5710: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5711: return ($outcome,$description);
1.1007 raeburn 5712: }
5713:
1.506 raeburn 5714: sub auto_create_password {
1.873 raeburn 5715: my ($cnum,$cdom,$authparam,$udom) = @_;
5716: my ($homeserver,$response);
1.506 raeburn 5717: my $create_passwd = 0;
5718: my $authchk = '';
1.873 raeburn 5719: if ($udom =~ /^$match_domain$/) {
5720: $homeserver = &domain($udom,'primary');
5721: }
5722: if ($homeserver eq '') {
5723: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5724: $homeserver = &homeserver($cnum,$cdom);
5725: }
5726: }
5727: if ($homeserver eq '') {
5728: $authchk = 'nodomain';
1.506 raeburn 5729: } else {
1.873 raeburn 5730: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5731: if ($response eq 'refused') {
5732: $authchk = 'refused';
5733: } else {
1.901 albertel 5734: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5735: }
1.506 raeburn 5736: }
5737: return ($authparam,$create_passwd,$authchk);
5738: }
5739:
1.706 raeburn 5740: sub auto_photo_permission {
5741: my ($cnum,$cdom,$students) = @_;
5742: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5743: my ($outcome,$perm_reqd,$conditions) =
5744: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5745: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5746: return (undef,undef);
5747: }
1.706 raeburn 5748: return ($outcome,$perm_reqd,$conditions);
5749: }
5750:
5751: sub auto_checkphotos {
5752: my ($uname,$udom,$pid) = @_;
5753: my $homeserver = &homeserver($uname,$udom);
5754: my ($result,$resulttype);
5755: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5756: &escape($uname).':'.&escape($pid),
5757: $homeserver));
1.709 albertel 5758: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5759: return (undef,undef);
5760: }
1.706 raeburn 5761: if ($outcome) {
5762: ($result,$resulttype) = split(/:/,$outcome);
5763: }
5764: return ($result,$resulttype);
5765: }
5766:
5767: sub auto_photochoice {
5768: my ($cnum,$cdom) = @_;
5769: my $homeserver = &homeserver($cnum,$cdom);
5770: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5771: &escape($cdom),
5772: $homeserver)));
1.709 albertel 5773: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5774: return (undef,undef);
5775: }
1.706 raeburn 5776: return ($update,$comment);
5777: }
5778:
5779: sub auto_photoupdate {
5780: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5781: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5782: my $host=&hostname($homeserver);
1.706 raeburn 5783: my $cmd = '';
5784: my $maxtries = 1;
1.800 albertel 5785: foreach my $affiliate (keys(%{$affiliatesref})) {
5786: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5787: }
5788: $cmd =~ s/%%$//;
5789: $cmd = &escape($cmd);
5790: my $query = 'institutionalphotos';
5791: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5792: unless ($queryid=~/^\Q$host\E\_/) {
5793: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5794: return 'error: '.$queryid;
5795: }
5796: my $reply = &get_query_reply($queryid);
5797: my $tries = 1;
5798: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5799: $reply = &get_query_reply($queryid);
5800: $tries ++;
5801: }
5802: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5803: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5804: } else {
5805: my @responses = split(/:/,$reply);
5806: my $outcome = shift(@responses);
5807: foreach my $item (@responses) {
5808: my ($key,$value) = split(/=/,$item);
5809: $$photo{$key} = $value;
5810: }
5811: return $outcome;
5812: }
5813: return 'error';
5814: }
5815:
1.521 raeburn 5816: sub auto_instcode_format {
1.793 albertel 5817: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5818: $cat_order) = @_;
1.521 raeburn 5819: my $courses = '';
1.772 raeburn 5820: my @homeservers;
1.521 raeburn 5821: if ($caller eq 'global') {
1.841 albertel 5822: my %servers = &get_servers($codedom,'library');
5823: foreach my $tryserver (keys(%servers)) {
5824: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5825: push(@homeservers,$tryserver);
5826: }
1.584 raeburn 5827: }
1.1022 raeburn 5828: } elsif ($caller eq 'requests') {
5829: if ($codedom =~ /^$match_domain$/) {
5830: my $chome = &domain($codedom,'primary');
5831: unless ($chome eq 'no_host') {
5832: push(@homeservers,$chome);
5833: }
5834: }
1.521 raeburn 5835: } else {
1.772 raeburn 5836: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5837: }
1.793 albertel 5838: foreach my $code (keys(%{$instcodes})) {
5839: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5840: }
5841: chop($courses);
1.772 raeburn 5842: my $ok_response = 0;
5843: my $response;
5844: while (@homeservers > 0 && $ok_response == 0) {
5845: my $server = shift(@homeservers);
5846: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5847: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5848: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5849: split(/:/,$response);
1.772 raeburn 5850: %{$codes} = (%{$codes},&str2hash($codes_str));
5851: push(@{$codetitles},&str2array($codetitles_str));
5852: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5853: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5854: $ok_response = 1;
5855: }
5856: }
5857: if ($ok_response) {
1.521 raeburn 5858: return 'ok';
1.772 raeburn 5859: } else {
5860: return $response;
1.521 raeburn 5861: }
5862: }
5863:
1.792 raeburn 5864: sub auto_instcode_defaults {
5865: my ($domain,$returnhash,$code_order) = @_;
5866: my @homeservers;
1.841 albertel 5867:
5868: my %servers = &get_servers($domain,'library');
5869: foreach my $tryserver (keys(%servers)) {
5870: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5871: push(@homeservers,$tryserver);
5872: }
1.792 raeburn 5873: }
1.841 albertel 5874:
1.792 raeburn 5875: my $response;
1.841 albertel 5876: foreach my $server (@homeservers) {
1.792 raeburn 5877: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5878: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5879:
5880: foreach my $pair (split(/\&/,$response)) {
5881: my ($name,$value)=split(/\=/,$pair);
5882: if ($name eq 'code_order') {
5883: @{$code_order} = split(/\&/,&unescape($value));
5884: } else {
5885: $returnhash->{&unescape($name)}=&unescape($value);
5886: }
5887: }
5888: return 'ok';
1.792 raeburn 5889: }
1.841 albertel 5890:
5891: return $response;
1.1003 raeburn 5892: }
5893:
5894: sub auto_possible_instcodes {
1.1007 raeburn 5895: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5896: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5897: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5898: return;
5899: }
1.1003 raeburn 5900: my (@homeservers,$uhome);
5901: if (defined(&domain($domain,'primary'))) {
5902: $uhome=&domain($domain,'primary');
5903: push(@homeservers,&domain($domain,'primary'));
5904: } else {
5905: my %servers = &get_servers($domain,'library');
5906: foreach my $tryserver (keys(%servers)) {
5907: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5908: push(@homeservers,$tryserver);
5909: }
5910: }
5911: }
5912: my $response;
5913: foreach my $server (@homeservers) {
5914: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5915: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5916: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5917: split(':',$response);
5918: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5919: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5920: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5921: my ($name,$value)=split('=',$item);
5922: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5923: }
5924: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5925: my ($name,$value)=split('=',$item);
5926: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5927: }
5928: return 'ok';
5929: }
5930: return $response;
5931: }
1.792 raeburn 5932:
1.1010 raeburn 5933: sub auto_courserequest_checks {
5934: my ($dom) = @_;
1.1020 raeburn 5935: my ($homeserver,%validations);
5936: if ($dom =~ /^$match_domain$/) {
5937: $homeserver = &domain($dom,'primary');
5938: }
5939: unless ($homeserver eq 'no_host') {
5940: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5941: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5942: my @items = split(/&/,$response);
5943: foreach my $item (@items) {
5944: my ($key,$value) = split('=',$item);
5945: $validations{&unescape($key)} = &thaw_unescape($value);
5946: }
5947: }
5948: }
1.1010 raeburn 5949: return %validations;
5950: }
5951:
1.1020 raeburn 5952: sub auto_courserequest_validation {
5953: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5954: my ($homeserver,$response);
5955: if ($dom =~ /^$match_domain$/) {
5956: $homeserver = &domain($dom,'primary');
5957: }
5958: unless ($homeserver eq 'no_host') {
1.1021 raeburn 5959:
1.1020 raeburn 5960: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 5961: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 5962: ':'.&escape($instcode).':'.&escape($instseclist),
5963: $homeserver));
5964: }
5965: return $response;
5966: }
5967:
1.777 albertel 5968: sub auto_validate_class_sec {
1.918 raeburn 5969: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5970: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5971: my $ownerlist;
5972: if (ref($owners) eq 'ARRAY') {
5973: $ownerlist = join(',',@{$owners});
5974: } else {
5975: $ownerlist = $owners;
5976: }
1.773 raeburn 5977: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5978: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5979: return $response;
5980: }
5981:
1.679 raeburn 5982: # ------------------------------------------------------- Course Group routines
5983:
5984: sub get_coursegroups {
1.809 raeburn 5985: my ($cdom,$cnum,$group,$namespace) = @_;
5986: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5987: }
5988:
1.679 raeburn 5989: sub modify_coursegroup {
5990: my ($cdom,$cnum,$groupsettings) = @_;
5991: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5992: }
5993:
1.809 raeburn 5994: sub toggle_coursegroup_status {
5995: my ($cdom,$cnum,$group,$action) = @_;
5996: my ($from_namespace,$to_namespace);
5997: if ($action eq 'delete') {
5998: $from_namespace = 'coursegroups';
5999: $to_namespace = 'deleted_groups';
6000: } else {
6001: $from_namespace = 'deleted_groups';
6002: $to_namespace = 'coursegroups';
6003: }
6004: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6005: if (my $tmp = &error(%curr_group)) {
6006: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6007: return ('read error',$tmp);
6008: } else {
6009: my %savedsettings = %curr_group;
1.809 raeburn 6010: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6011: my $deloutcome;
6012: if ($result eq 'ok') {
1.809 raeburn 6013: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6014: } else {
6015: return ('write error',$result);
6016: }
6017: if ($deloutcome eq 'ok') {
6018: return 'ok';
6019: } else {
6020: return ('delete error',$deloutcome);
6021: }
6022: }
6023: }
6024:
1.679 raeburn 6025: sub modify_group_roles {
1.957 raeburn 6026: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6027: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6028: my $role = 'gr/'.&escape($userprivs);
6029: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6030: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6031: if ($result eq 'ok') {
6032: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6033: }
1.679 raeburn 6034: return $result;
6035: }
6036:
6037: sub modify_coursegroup_membership {
6038: my ($cdom,$cnum,$membership) = @_;
6039: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6040: return $result;
6041: }
6042:
1.682 raeburn 6043: sub get_active_groups {
6044: my ($udom,$uname,$cdom,$cnum) = @_;
6045: my $now = time;
6046: my %groups = ();
6047: foreach my $key (keys(%env)) {
1.811 albertel 6048: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6049: my ($start,$end) = split(/\./,$env{$key});
6050: if (($end!=0) && ($end<$now)) { next; }
6051: if (($start!=0) && ($start>$now)) { next; }
6052: if ($1 eq $cdom && $2 eq $cnum) {
6053: $groups{$3} = $env{$key} ;
6054: }
6055: }
6056: }
6057: return %groups;
6058: }
6059:
1.683 raeburn 6060: sub get_group_membership {
6061: my ($cdom,$cnum,$group) = @_;
6062: return(&dump('groupmembership',$cdom,$cnum,$group));
6063: }
6064:
6065: sub get_users_groups {
6066: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6067: my @usersgroups;
1.683 raeburn 6068: my $cachetime=1800;
6069:
6070: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6071: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6072: if (defined($cached)) {
1.734 albertel 6073: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6074: } else {
6075: $grouplist = '';
1.816 raeburn 6076: my $courseurl = &courseid_to_courseurl($courseid);
6077: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6078: my $access_end = $env{'course.'.$courseid.
6079: '.default_enrollment_end_date'};
6080: my $now = time;
6081: foreach my $key (keys(%roleshash)) {
6082: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6083: my $group = $1;
6084: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6085: my $start = $2;
6086: my $end = $1;
6087: if ($start == -1) { next; } # deleted from group
6088: if (($start!=0) && ($start>$now)) { next; }
6089: if (($end!=0) && ($end<$now)) {
6090: if ($access_end && $access_end < $now) {
6091: if ($access_end - $end < 86400) {
6092: push(@usersgroups,$group);
1.733 raeburn 6093: }
6094: }
1.817 raeburn 6095: next;
1.733 raeburn 6096: }
1.817 raeburn 6097: push(@usersgroups,$group);
1.683 raeburn 6098: }
6099: }
6100: }
1.817 raeburn 6101: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6102: $grouplist = join(':',@usersgroups);
6103: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6104: }
1.733 raeburn 6105: return @usersgroups;
1.683 raeburn 6106: }
6107:
6108: sub devalidate_getgroups_cache {
6109: my ($udom,$uname,$cdom,$cnum)=@_;
6110: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6111:
1.683 raeburn 6112: my $hashid="$udom:$uname:$courseid";
6113: &devalidate_cache_new('getgroups',$hashid);
6114: }
6115:
1.12 www 6116: # ------------------------------------------------------------------ Plain Text
6117:
6118: sub plaintext {
1.988 raeburn 6119: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6120: if ($short =~ m{^cr/}) {
1.758 albertel 6121: return (split('/',$short))[-1];
6122: }
1.742 raeburn 6123: if (!defined($cid)) {
6124: $cid = $env{'request.course.id'};
6125: }
6126: my %rolenames = (
1.1008 raeburn 6127: Course => 'std',
6128: Community => 'alt1',
1.742 raeburn 6129: );
1.1037 raeburn 6130: if ($cid ne '') {
6131: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6132: unless ($forcedefault) {
6133: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6134: &Apache::lonlocal::mt_escape(\$roletext);
6135: return &Apache::lonlocal::mt($roletext);
6136: }
6137: }
6138: }
6139: if ((defined($type)) && (defined($rolenames{$type})) &&
6140: (defined($rolenames{$type})) &&
6141: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6142: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6143: } elsif ($cid ne '') {
6144: my $crstype = $env{'course.'.$cid.'.type'};
6145: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6146: (defined($prp{$short}{$rolenames{$crstype}}))) {
6147: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6148: }
1.742 raeburn 6149: }
1.1037 raeburn 6150: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6151: }
6152:
6153: # ----------------------------------------------------------------- Assign Role
6154:
6155: sub assignrole {
1.957 raeburn 6156: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6157: $context)=@_;
1.21 www 6158: my $mrole;
6159: if ($role =~ /^cr\//) {
1.393 www 6160: my $cwosec=$url;
1.811 albertel 6161: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6162: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6163: my $refused = 1;
6164: if ($context eq 'requestcourses') {
6165: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6166: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6167: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6168: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6169: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6170: if ($crsenv{'internal.courseowner'} eq
6171: $env{'user.name'}.':'.$env{'user.domain'}) {
6172: $refused = '';
6173: }
6174: }
6175: }
6176: }
6177: }
6178: if ($refused) {
6179: &logthis('Refused custom assignrole: '.
6180: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6181: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6182: return 'refused';
6183: }
1.104 www 6184: }
1.21 www 6185: $mrole='cr';
1.678 raeburn 6186: } elsif ($role =~ /^gr\//) {
6187: my $cwogrp=$url;
1.811 albertel 6188: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6189: unless (&allowed('mdg',$cwogrp)) {
6190: &logthis('Refused group assignrole: '.
6191: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6192: $env{'user.name'}.' at '.$env{'user.domain'});
6193: return 'refused';
6194: }
6195: $mrole='gr';
1.21 www 6196: } else {
1.82 www 6197: my $cwosec=$url;
1.811 albertel 6198: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6199: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6200: my $refused;
6201: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6202: if (!(&allowed('c'.$role,$url))) {
6203: $refused = 1;
6204: }
6205: } else {
6206: $refused = 1;
6207: }
1.947 raeburn 6208: if ($refused) {
1.1045 raeburn 6209: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6210: if (!$selfenroll && $context eq 'course') {
6211: my %crsenv;
6212: if ($role eq 'cc' || $role eq 'co') {
6213: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6214: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6215: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6216: if ($crsenv{'internal.courseowner'} eq
6217: $env{'user.name'}.':'.$env{'user.domain'}) {
6218: $refused = '';
6219: }
6220: }
6221: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6222: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6223: if ($crsenv{'internal.courseowner'} eq
6224: $env{'user.name'}.':'.$env{'user.domain'}) {
6225: $refused = '';
6226: }
6227: }
6228: }
6229: }
6230: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6231: $refused = '';
1.1017 raeburn 6232: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6233: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6234: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6235: my $wrongcc;
6236: if ($cnum =~ /^$match_community$/) {
6237: $wrongcc = 1 if ($role eq 'cc');
6238: } else {
6239: $wrongcc = 1 if ($role eq 'co');
6240: }
6241: unless ($wrongcc) {
6242: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6243: if ($crsenv{'internal.courseowner'} eq
6244: $env{'user.name'}.':'.$env{'user.domain'}) {
6245: $refused = '';
6246: }
1.1017 raeburn 6247: }
6248: }
6249: }
6250: if ($refused) {
1.947 raeburn 6251: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6252: ' '.$role.' '.$end.' '.$start.' by '.
6253: $env{'user.name'}.' at '.$env{'user.domain'});
6254: return 'refused';
6255: }
1.932 raeburn 6256: }
1.104 www 6257: }
1.21 www 6258: $mrole=$role;
6259: }
1.620 albertel 6260: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6261: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6262: if ($end) { $command.='_'.$end; }
1.21 www 6263: if ($start) {
6264: if ($end) {
1.81 www 6265: $command.='_'.$start;
1.21 www 6266: } else {
1.81 www 6267: $command.='_0_'.$start;
1.21 www 6268: }
6269: }
1.739 raeburn 6270: my $origstart = $start;
6271: my $origend = $end;
1.957 raeburn 6272: my $delflag;
1.357 www 6273: # actually delete
6274: if ($deleteflag) {
1.373 www 6275: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6276: # modify command to delete the role
1.620 albertel 6277: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6278: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6279: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6280: # set start and finish to negative values for userrolelog
6281: $start=-1;
6282: $end=-1;
1.957 raeburn 6283: $delflag = 1;
1.357 www 6284: }
6285: }
6286: # send command
1.349 www 6287: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6288: # log new user role if status is ok
1.349 www 6289: if ($answer eq 'ok') {
1.663 raeburn 6290: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6291: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6292: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6293: unless ($role =~ /^gr/) {
6294: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6295: $origstart,$selfenroll,$context);
1.739 raeburn 6296: }
1.1053 raeburn 6297: if ($role eq 'cc') {
6298: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6299: }
1.349 www 6300: }
6301: return $answer;
1.169 harris41 6302: }
6303:
1.1053 raeburn 6304: sub autoupdate_coowners {
6305: my ($url,$end,$start,$uname,$udom) = @_;
6306: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6307: if (($cdom ne '') && ($cnum ne '')) {
6308: my $now = time;
6309: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6310: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6311: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6312: my $instcode = $coursehash{'internal.coursecode'};
6313: if ($instcode ne '') {
1.1056 raeburn 6314: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6315: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6316: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6317: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6318: if ($result eq 'valid') {
6319: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6320: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6321: push(@newcoowners,$coowner);
6322: }
6323: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6324: push(@newcoowners,$uname.':'.$udom);
6325: }
6326: @newcoowners = sort(@newcoowners);
6327: } else {
6328: push(@newcoowners,$uname.':'.$udom);
6329: }
6330: } else {
6331: if ($coursehash{'internal.co-owners'}) {
6332: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6333: unless ($coowner eq $uname.':'.$udom) {
6334: push(@newcoowners,$coowner);
6335: }
6336: }
6337: unless (@newcoowners > 0) {
6338: $delcoowners = 1;
6339: $coowners = '';
6340: }
6341: }
6342: }
6343: if (@newcoowners || $delcoowners) {
6344: &store_coowners($cdom,$cnum,$coursehash{'home'},
6345: $delcoowners,@newcoowners);
6346: }
6347: }
6348: }
6349: }
6350: }
6351: }
6352: }
6353:
6354: sub store_coowners {
6355: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6356: my $cid = $cdom.'_'.$cnum;
6357: my ($coowners,$delresult,$putresult);
6358: if (@newcoowners) {
6359: $coowners = join(',',@newcoowners);
6360: my %coownershash = (
6361: 'internal.co-owners' => $coowners,
6362: );
6363: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6364: if ($putresult eq 'ok') {
6365: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6366: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6367: }
6368: }
6369: }
6370: if ($delcoowners) {
6371: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6372: if ($delresult eq 'ok') {
6373: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6374: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6375: }
6376: }
6377: }
6378: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6379: my %crsinfo =
6380: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6381: if (ref($crsinfo{$cid}) eq 'HASH') {
6382: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6383: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6384: }
6385: }
6386: }
6387:
1.169 harris41 6388: # -------------------------------------------------- Modify user authentication
1.197 www 6389: # Overrides without validation
6390:
1.169 harris41 6391: sub modifyuserauth {
6392: my ($udom,$uname,$umode,$upass)=@_;
6393: my $uhome=&homeserver($uname,$udom);
1.197 www 6394: unless (&allowed('mau',$udom)) { return 'refused'; }
6395: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6396: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6397: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6398: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6399: &escape($upass),$uhome);
1.620 albertel 6400: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6401: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6402: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6403: &log($udom,,$uname,$uhome,
1.620 albertel 6404: 'Authentication changed by '.$env{'user.domain'}.', '.
6405: $env{'user.name'}.', '.$umode.
1.197 www 6406: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6407: unless ($reply eq 'ok') {
1.197 www 6408: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6409: return 'error: '.$reply;
6410: }
1.170 harris41 6411: return 'ok';
1.80 www 6412: }
6413:
1.81 www 6414: # --------------------------------------------------------------- Modify a user
1.80 www 6415:
1.81 www 6416: sub modifyuser {
1.206 matthew 6417: my ($udom, $uname, $uid,
6418: $umode, $upass, $first,
6419: $middle, $last, $gene,
1.1058 raeburn 6420: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6421: $udom= &LONCAPA::clean_domain($udom);
6422: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6423: my $showcandelete = 'none';
6424: if (ref($candelete) eq 'ARRAY') {
6425: if (@{$candelete} > 0) {
6426: $showcandelete = join(', ',@{$candelete});
6427: }
6428: }
1.81 www 6429: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6430: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6431: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6432: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6433: ' desiredhome not specified').
1.620 albertel 6434: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6435: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6436: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6437: # ----------------------------------------------------------------- Create User
1.406 albertel 6438: if (($uhome eq 'no_host') &&
6439: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6440: my $unhome='';
1.844 albertel 6441: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6442: $unhome = $desiredhome;
1.620 albertel 6443: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6444: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6445: } else { # load balancing routine for determining $unhome
1.81 www 6446: my $loadm=10000000;
1.841 albertel 6447: my %servers = &get_servers($udom,'library');
6448: foreach my $tryserver (keys(%servers)) {
6449: my $answer=reply('load',$tryserver);
6450: if (($answer=~/\d+/) && ($answer<$loadm)) {
6451: $loadm=$answer;
6452: $unhome=$tryserver;
6453: }
1.80 www 6454: }
6455: }
6456: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6457: return 'error: unable to find a home server for '.$uname.
6458: ' in domain '.$udom;
1.80 www 6459: }
6460: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6461: &escape($upass),$unhome);
6462: unless ($reply eq 'ok') {
6463: return 'error: '.$reply;
6464: }
1.230 stredwic 6465: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6466: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6467: return 'error: unable verify users home machine.';
1.80 www 6468: }
1.209 matthew 6469: } # End of creation of new user
1.80 www 6470: # ---------------------------------------------------------------------- Add ID
6471: if ($uid) {
6472: $uid=~tr/A-Z/a-z/;
6473: my %uidhash=&idrget($udom,$uname);
1.196 www 6474: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6475: && (!$forceid)) {
1.80 www 6476: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6477: return 'error: user id "'.$uid.'" does not match '.
6478: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6479: }
6480: } else {
6481: &idput($udom,($uname => $uid));
6482: }
6483: }
6484: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6485: my @tmp=&get('environment',
1.899 raeburn 6486: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6487: 'permanentemail','inststatus'],
1.134 albertel 6488: $udom,$uname);
1.313 matthew 6489: my %names;
6490: if ($tmp[0] =~ m/^error:.*/) {
6491: %names=();
6492: } else {
6493: %names = @tmp;
6494: }
1.388 www 6495: #
1.1058 raeburn 6496: # If name, email and/or uid are blank (e.g., because an uploaded file
6497: # of users did not contain them), do not overwrite existing values
6498: # unless field is in $candelete array ref.
6499: #
6500:
6501: my @fields = ('firstname','middlename','lastname','generation',
6502: 'permanentemail','id');
6503: my %newvalues;
6504: if (ref($candelete) eq 'ARRAY') {
6505: foreach my $field (@fields) {
6506: if (grep(/^\Q$field\E$/,@{$candelete})) {
6507: if ($field eq 'firstname') {
6508: $names{$field} = $first;
6509: } elsif ($field eq 'middlename') {
6510: $names{$field} = $middle;
6511: } elsif ($field eq 'lastname') {
6512: $names{$field} = $last;
6513: } elsif ($field eq 'generation') {
6514: $names{$field} = $gene;
6515: } elsif ($field eq 'permanentemail') {
6516: $names{$field} = $email;
6517: } elsif ($field eq 'id') {
6518: $names{$field} = $uid;
6519: }
6520: }
6521: }
6522: }
1.388 www 6523: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6524: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6525: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6526: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6527: if ($email) {
6528: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6529: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6530: }
1.899 raeburn 6531: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6532: if (defined($inststatus)) {
6533: $names{'inststatus'} = '';
6534: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6535: if (ref($usertypes) eq 'HASH') {
6536: my @okstatuses;
6537: foreach my $item (split(/:/,$inststatus)) {
6538: if (defined($usertypes->{$item})) {
6539: push(@okstatuses,$item);
6540: }
6541: }
6542: if (@okstatuses) {
6543: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6544: }
6545: }
6546: }
1.134 albertel 6547: my $reply = &put('environment', \%names, $udom,$uname);
6548: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6549: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6550: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6551: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6552: $umode.', '.$first.', '.$middle.', '.
6553: $last.', '.$gene.', '.$email.', '.$inststatus;
6554: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6555: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6556: } else {
6557: $logmsg .= ' during self creation';
6558: }
6559: &logthis($logmsg);
1.134 albertel 6560: return 'ok';
1.80 www 6561: }
6562:
1.81 www 6563: # -------------------------------------------------------------- Modify student
1.80 www 6564:
1.81 www 6565: sub modifystudent {
6566: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6567: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6568: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6569: if (!$cid) {
1.620 albertel 6570: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6571: return 'not_in_class';
6572: }
1.80 www 6573: }
6574: # --------------------------------------------------------------- Make the user
1.81 www 6575: my $reply=&modifyuser
1.209 matthew 6576: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6577: $desiredhome,$email,$inststatus);
1.80 www 6578: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6579: # This will cause &modify_student_enrollment to get the uid from the
6580: # students environment
6581: $uid = undef if (!$forceid);
1.455 albertel 6582: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6583: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6584: return $reply;
6585: }
6586:
6587: sub modify_student_enrollment {
1.957 raeburn 6588: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6589: my ($cdom,$cnum,$chome);
6590: if (!$cid) {
1.620 albertel 6591: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6592: return 'not_in_class';
6593: }
1.620 albertel 6594: $cdom=$env{'course.'.$cid.'.domain'};
6595: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6596: } else {
6597: ($cdom,$cnum)=split(/_/,$cid);
6598: }
1.620 albertel 6599: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6600: if (!$chome) {
1.457 raeburn 6601: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6602: }
1.455 albertel 6603: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6604: # Make sure the user exists
1.81 www 6605: my $uhome=&homeserver($uname,$udom);
6606: if (($uhome eq '') || ($uhome eq 'no_host')) {
6607: return 'error: no such user';
6608: }
1.297 matthew 6609: # Get student data if we were not given enough information
6610: if (!defined($first) || $first eq '' ||
6611: !defined($last) || $last eq '' ||
6612: !defined($uid) || $uid eq '' ||
6613: !defined($middle) || $middle eq '' ||
6614: !defined($gene) || $gene eq '') {
1.294 matthew 6615: # They did not supply us with enough data to enroll the student, so
6616: # we need to pick up more information.
1.297 matthew 6617: my %tmp = &get('environment',
1.294 matthew 6618: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6619: ,$udom,$uname);
6620:
1.800 albertel 6621: #foreach my $key (keys(%tmp)) {
6622: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6623: #}
1.294 matthew 6624: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6625: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6626: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6627: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6628: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6629: }
1.556 albertel 6630: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6631: my $reply=cput('classlist',
6632: {"$uname:$udom" =>
1.515 raeburn 6633: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6634: $cdom,$cnum);
1.81 www 6635: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6636: return 'error: '.$reply;
1.652 albertel 6637: } else {
6638: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6639: }
1.297 matthew 6640: # Add student role to user
1.83 www 6641: my $uurl='/'.$cid;
1.81 www 6642: $uurl=~s/\_/\//g;
6643: if ($usec) {
6644: $uurl.='/'.$usec;
6645: }
1.957 raeburn 6646: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6647: }
6648:
1.556 albertel 6649: sub format_name {
6650: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6651: my $name;
6652: if ($first ne 'lastname') {
6653: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6654: } else {
6655: if ($lastname=~/\S/) {
6656: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6657: $name=~s/\s+,/,/;
6658: } else {
6659: $name.= $firstname.' '.$middlename.' '.$generation;
6660: }
6661: }
6662: $name=~s/^\s+//;
6663: $name=~s/\s+$//;
6664: $name=~s/\s+/ /g;
6665: return $name;
6666: }
6667:
1.84 www 6668: # ------------------------------------------------- Write to course preferences
6669:
6670: sub writecoursepref {
6671: my ($courseid,%prefs)=@_;
6672: $courseid=~s/^\///;
6673: $courseid=~s/\_/\//g;
6674: my ($cdomain,$cnum)=split(/\//,$courseid);
6675: my $chome=homeserver($cnum,$cdomain);
6676: if (($chome eq '') || ($chome eq 'no_host')) {
6677: return 'error: no such course';
6678: }
6679: my $cstring='';
1.800 albertel 6680: foreach my $pref (keys(%prefs)) {
6681: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6682: }
1.84 www 6683: $cstring=~s/\&$//;
6684: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6685: }
6686:
6687: # ---------------------------------------------------------- Make/modify course
6688:
6689: sub createcourse {
1.741 raeburn 6690: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6691: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6692: $url=&declutter($url);
6693: my $cid='';
1.1028 raeburn 6694: if ($context eq 'requestcourses') {
6695: my $can_create = 0;
6696: my ($ownername,$ownerdom) = split(':',$course_owner);
6697: if ($udom eq $ownerdom) {
6698: if (&usertools_access($ownername,$ownerdom,$category,undef,
6699: $context)) {
6700: $can_create = 1;
6701: }
6702: } else {
6703: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6704: $category);
6705: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6706: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6707: if (@curr > 0) {
6708: my @options = qw(approval validate autolimit);
6709: my $optregex = join('|',@options);
6710: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6711: $can_create = 1;
6712: }
6713: }
6714: }
6715: }
6716: if ($can_create) {
6717: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6718: unless (&allowed('ccc',$udom)) {
6719: return 'refused';
6720: }
1.1017 raeburn 6721: }
6722: } else {
6723: return 'refused';
6724: }
1.1028 raeburn 6725: } elsif (!&allowed('ccc',$udom)) {
6726: return 'refused';
1.84 www 6727: }
1.1011 raeburn 6728: # --------------------------------------------------------------- Get Unique ID
6729: my $uname;
6730: if ($cnum =~ /^$match_courseid$/) {
6731: my $chome=&homeserver($cnum,$udom,'true');
6732: if (($chome eq '') || ($chome eq 'no_host')) {
6733: $uname = $cnum;
6734: } else {
1.1038 raeburn 6735: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6736: }
6737: } else {
1.1038 raeburn 6738: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6739: }
6740: return $uname if ($uname =~ /^error/);
6741: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6742: if (!defined($course_server)) {
6743: if (defined(&domain($udom,'primary'))) {
6744: $course_server = &domain($udom,'primary');
6745: } else {
6746: $course_server = $env{'user.home'};
6747: }
6748: }
6749: my %host_servers =
6750: &Apache::lonnet::get_servers($udom,'library');
6751: unless ($host_servers{$course_server}) {
6752: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6753: }
1.84 www 6754: # ------------------------------------------------------------- Make the course
6755: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6756: $course_server);
1.84 www 6757: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6758: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6759: if (($uhome eq '') || ($uhome eq 'no_host')) {
6760: return 'error: no such course';
6761: }
1.271 www 6762: # ----------------------------------------------------------------- Course made
1.516 raeburn 6763: # log existence
1.1029 raeburn 6764: my $now = time;
1.918 raeburn 6765: my $newcourse = {
6766: $udom.'_'.$uname => {
1.921 raeburn 6767: description => $description,
6768: inst_code => $inst_code,
6769: owner => $course_owner,
6770: type => $crstype,
1.1029 raeburn 6771: creator => $env{'user.name'}.':'.
6772: $env{'user.domain'},
6773: created => $now,
6774: context => $context,
1.918 raeburn 6775: },
6776: };
1.921 raeburn 6777: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6778: # set toplevel url
1.271 www 6779: my $topurl=$url;
6780: unless ($nonstandard) {
6781: # ------------------------------------------ For standard courses, make top url
6782: my $mapurl=&clutter($url);
1.278 www 6783: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6784: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6785: <map>
6786: <resource id="1" type="start"></resource>
6787: <resource id="2" src="$mapurl"></resource>
6788: <resource id="3" type="finish"></resource>
6789: <link index="1" from="1" to="2"></link>
6790: <link index="2" from="2" to="3"></link>
6791: </map>
6792: ENDINITMAP
6793: $topurl=&declutter(
1.638 albertel 6794: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6795: );
6796: }
6797: # ----------------------------------------------------------- Write preferences
1.84 www 6798: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6799: ('description' => $description,
6800: 'url' => $topurl,
6801: 'internal.creator' => $env{'user.name'}.':'.
6802: $env{'user.domain'},
6803: 'internal.created' => $now,
6804: 'internal.creationcontext' => $context)
6805: );
1.84 www 6806: return '/'.$udom.'/'.$uname;
6807: }
6808:
1.1011 raeburn 6809: # ------------------------------------------------------------------- Create ID
6810: sub generate_coursenum {
1.1038 raeburn 6811: my ($udom,$crstype) = @_;
1.1011 raeburn 6812: my $domdesc = &domain($udom);
6813: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 6814: my $first;
6815: if ($crstype eq 'Community') {
6816: $first = '0';
6817: } else {
6818: $first = int(1+rand(9));
6819: }
6820: my $uname=$first.
1.1011 raeburn 6821: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6822: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6823: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6824: # ----------------------------------------------- Make sure that does not exist
6825: my $uhome=&homeserver($uname,$udom,'true');
6826: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 6827: if ($crstype eq 'Community') {
6828: $first = '0';
6829: } else {
6830: $first = int(1+rand(9));
6831: }
6832: $uname=$first.
1.1011 raeburn 6833: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6834: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6835: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6836: $uhome=&homeserver($uname,$udom,'true');
6837: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6838: return 'error: unable to generate unique course-ID';
6839: }
6840: }
6841: return $uname;
6842: }
6843:
1.813 albertel 6844: sub is_course {
6845: my ($cdom,$cnum) = @_;
6846: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6847: undef,'.');
1.813 albertel 6848: if (exists($courses{$cdom.'_'.$cnum})) {
6849: return 1;
6850: }
6851: return 0;
6852: }
6853:
1.1015 raeburn 6854: sub store_userdata {
6855: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 6856: my $result;
1.1016 raeburn 6857: if ($datakey ne '') {
1.1013 raeburn 6858: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 6859: if ($udom eq '' || $uname eq '') {
6860: $udom = $env{'user.domain'};
6861: $uname = $env{'user.name'};
6862: }
6863: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 6864: if (($uhome eq '') || ($uhome eq 'no_host')) {
6865: $result = 'error: no_host';
6866: } else {
6867: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6868: $storehash->{'host'} = $perlvar{'lonHostID'};
6869:
6870: my $namevalue='';
6871: foreach my $key (keys(%{$storehash})) {
6872: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6873: }
6874: $namevalue=~s/\&$//;
6875: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 6876: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 6877: }
6878: } else {
6879: $result = 'error: data to store was not a hash reference';
6880: }
6881: } else {
6882: $result= 'error: invalid requestkey';
6883: }
6884: return $result;
6885: }
6886:
1.21 www 6887: # ---------------------------------------------------------- Assign Custom Role
6888:
6889: sub assigncustomrole {
1.957 raeburn 6890: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6891: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6892: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6893: }
6894:
6895: # ----------------------------------------------------------------- Revoke Role
6896:
6897: sub revokerole {
1.957 raeburn 6898: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6899: my $now=time;
1.965 raeburn 6900: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6901: }
6902:
6903: # ---------------------------------------------------------- Revoke Custom Role
6904:
6905: sub revokecustomrole {
1.957 raeburn 6906: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6907: my $now=time;
1.357 www 6908: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6909: $deleteflag,$selfenroll,$context);
1.17 www 6910: }
6911:
1.533 banghart 6912: # ------------------------------------------------------------ Disk usage
1.535 albertel 6913: sub diskusage {
1.955 raeburn 6914: my ($udom,$uname,$directorypath,$getpropath)=@_;
6915: $directorypath =~ s/\/$//;
6916: my $listing=&reply('du2:'.&escape($directorypath).':'
6917: .&escape($getpropath).':'.&escape($uname).':'
6918: .&escape($udom),homeserver($uname,$udom));
6919: if ($listing eq 'unknown_cmd') {
6920: if ($getpropath) {
6921: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6922: }
6923: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6924: }
1.514 albertel 6925: return $listing;
1.512 banghart 6926: }
6927:
1.566 banghart 6928: sub is_locked {
6929: my ($file_name, $domain, $user) = @_;
6930: my @check;
6931: my $is_locked;
6932: push @check, $file_name;
1.613 albertel 6933: my %locked = &get('file_permissions',\@check,
1.620 albertel 6934: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6935: my ($tmp)=keys(%locked);
6936: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6937:
1.566 banghart 6938: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6939: $is_locked = 'false';
6940: foreach my $entry (@{$locked{$file_name}}) {
6941: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6942: $is_locked = 'true';
6943: last;
1.745 raeburn 6944: }
6945: }
1.566 banghart 6946: } else {
6947: $is_locked = 'false';
6948: }
6949: }
6950:
1.759 albertel 6951: sub declutter_portfile {
6952: my ($file) = @_;
1.833 albertel 6953: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6954: return $file;
6955: }
6956:
1.559 banghart 6957: # ------------------------------------------------------------- Mark as Read Only
6958:
6959: sub mark_as_readonly {
6960: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6961: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6962: my ($tmp)=keys(%current_permissions);
6963: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6964: foreach my $file (@{$files}) {
1.759 albertel 6965: $file = &declutter_portfile($file);
1.561 banghart 6966: push(@{$current_permissions{$file}},$what);
1.559 banghart 6967: }
1.613 albertel 6968: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6969: return;
6970: }
6971:
1.572 banghart 6972: # ------------------------------------------------------------Save Selected Files
6973:
6974: sub save_selected_files {
6975: my ($user, $path, @files) = @_;
6976: my $filename = $user."savedfiles";
1.573 banghart 6977: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6978: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6979: foreach my $file (@files) {
1.620 albertel 6980: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6981: }
6982: foreach my $file (@other_files) {
1.574 banghart 6983: print (OUT $file."\n");
1.572 banghart 6984: }
1.574 banghart 6985: close (OUT);
1.572 banghart 6986: return 'ok';
6987: }
6988:
1.574 banghart 6989: sub clear_selected_files {
6990: my ($user) = @_;
6991: my $filename = $user."savedfiles";
6992: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6993: print (OUT undef);
6994: close (OUT);
6995: return ("ok");
6996: }
6997:
1.572 banghart 6998: sub files_in_path {
6999: my ($user, $path) = @_;
7000: my $filename = $user."savedfiles";
7001: my %return_files;
1.574 banghart 7002: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7003: while (my $line_in = <IN>) {
1.574 banghart 7004: chomp ($line_in);
7005: my @paths_and_file = split (m!/!, $line_in);
7006: my $file_part = pop (@paths_and_file);
7007: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7008: $path_part.='/';
7009: my $path_and_file = $path_part.$file_part;
7010: if ($path_part eq $path) {
7011: $return_files{$file_part}= 'selected';
7012: }
7013: }
1.574 banghart 7014: close (IN);
7015: return (\%return_files);
1.572 banghart 7016: }
7017:
7018: # called in portfolio select mode, to show files selected NOT in current directory
7019: sub files_not_in_path {
7020: my ($user, $path) = @_;
7021: my $filename = $user."savedfiles";
7022: my @return_files;
7023: my $path_part;
1.800 albertel 7024: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7025: while (my $line = <IN>) {
1.572 banghart 7026: #ok, I know it's clunky, but I want it to work
1.800 albertel 7027: my @paths_and_file = split(m|/|, $line);
7028: my $file_part = pop(@paths_and_file);
7029: chomp($file_part);
7030: my $path_part = join('/', @paths_and_file);
1.572 banghart 7031: $path_part .= '/';
7032: my $path_and_file = $path_part.$file_part;
7033: if ($path_part ne $path) {
1.800 albertel 7034: push(@return_files, ($path_and_file));
1.572 banghart 7035: }
7036: }
1.800 albertel 7037: close(OUT);
1.574 banghart 7038: return (@return_files);
1.572 banghart 7039: }
7040:
1.745 raeburn 7041: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7042:
1.745 raeburn 7043: sub get_portfile_permissions {
7044: my ($domain,$user) = @_;
1.613 albertel 7045: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7046: my ($tmp)=keys(%current_permissions);
7047: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7048: return \%current_permissions;
7049: }
7050:
7051: #---------------------------------------------Get portfolio file access controls
7052:
1.749 raeburn 7053: sub get_access_controls {
1.745 raeburn 7054: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7055: my %access;
7056: my $real_file = $file;
7057: $file =~ s/\.meta$//;
1.745 raeburn 7058: if (defined($file)) {
1.749 raeburn 7059: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7060: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7061: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7062: }
7063: }
1.745 raeburn 7064: } else {
1.749 raeburn 7065: foreach my $key (keys(%{$current_permissions})) {
7066: if ($key =~ /\0accesscontrol$/) {
7067: if (defined($group)) {
7068: if ($key !~ m-^\Q$group\E/-) {
7069: next;
7070: }
7071: }
7072: my ($fullpath) = split(/\0/,$key);
7073: if (ref($$current_permissions{$key}) eq 'HASH') {
7074: foreach my $control (keys(%{$$current_permissions{$key}})) {
7075: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7076: }
7077: }
7078: }
7079: }
7080: }
7081: return %access;
7082: }
7083:
7084: sub modify_access_controls {
7085: my ($file_name,$changes,$domain,$user)=@_;
7086: my ($outcome,$deloutcome);
7087: my %store_permissions;
7088: my %new_values;
7089: my %new_control;
7090: my %translation;
7091: my @deletions = ();
7092: my $now = time;
7093: if (exists($$changes{'activate'})) {
7094: if (ref($$changes{'activate'}) eq 'HASH') {
7095: my @newitems = sort(keys(%{$$changes{'activate'}}));
7096: my $numnew = scalar(@newitems);
7097: for (my $i=0; $i<$numnew; $i++) {
7098: my $newkey = $newitems[$i];
7099: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7100: if ($newkey =~ /^\d+:/) {
7101: $newkey =~ s/^(\d+)/$newid/;
7102: $translation{$1} = $newid;
7103: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7104: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7105: $translation{$1} = $newid;
7106: }
1.749 raeburn 7107: $new_values{$file_name."\0".$newkey} =
7108: $$changes{'activate'}{$newitems[$i]};
7109: $new_control{$newkey} = $now;
7110: }
7111: }
7112: }
7113: my %todelete;
7114: my %changed_items;
7115: foreach my $action ('delete','update') {
7116: if (exists($$changes{$action})) {
7117: if (ref($$changes{$action}) eq 'HASH') {
7118: foreach my $key (keys(%{$$changes{$action}})) {
7119: my ($itemnum) = ($key =~ /^([^:]+):/);
7120: if ($action eq 'delete') {
7121: $todelete{$itemnum} = 1;
7122: } else {
7123: $changed_items{$itemnum} = $key;
7124: }
7125: }
1.745 raeburn 7126: }
7127: }
1.749 raeburn 7128: }
7129: # get lock on access controls for file.
7130: my $lockhash = {
7131: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7132: ':'.$env{'user.domain'},
7133: };
7134: my $tries = 0;
7135: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7136:
7137: while (($gotlock ne 'ok') && $tries <3) {
7138: $tries ++;
7139: sleep 1;
7140: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7141: }
7142: if ($gotlock eq 'ok') {
7143: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7144: my ($tmp)=keys(%curr_permissions);
7145: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7146: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7147: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7148: if (ref($curr_controls) eq 'HASH') {
7149: foreach my $control_item (keys(%{$curr_controls})) {
7150: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7151: if (defined($todelete{$itemnum})) {
7152: push(@deletions,$file_name."\0".$control_item);
7153: } else {
7154: if (defined($changed_items{$itemnum})) {
7155: $new_control{$changed_items{$itemnum}} = $now;
7156: push(@deletions,$file_name."\0".$control_item);
7157: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7158: } else {
7159: $new_control{$control_item} = $$curr_controls{$control_item};
7160: }
7161: }
1.745 raeburn 7162: }
7163: }
7164: }
1.970 raeburn 7165: my ($group);
7166: if (&is_course($domain,$user)) {
7167: ($group,my $file) = split(/\//,$file_name,2);
7168: }
1.749 raeburn 7169: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7170: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7171: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7172: # remove lock
7173: my @del_lock = ($file_name."\0".'locked_access_records');
7174: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7175: my $sqlresult =
1.970 raeburn 7176: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7177: $group);
1.749 raeburn 7178: } else {
7179: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7180: }
1.749 raeburn 7181: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7182: }
7183:
1.827 raeburn 7184: sub make_public_indefinitely {
7185: my ($requrl) = @_;
7186: my $now = time;
7187: my $action = 'activate';
7188: my $aclnum = 0;
7189: if (&is_portfolio_url($requrl)) {
7190: my (undef,$udom,$unum,$file_name,$group) =
7191: &parse_portfolio_url($requrl);
7192: my $current_perms = &get_portfile_permissions($udom,$unum);
7193: my %access_controls = &get_access_controls($current_perms,
7194: $group,$file_name);
7195: foreach my $key (keys(%{$access_controls{$file_name}})) {
7196: my ($num,$scope,$end,$start) =
7197: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7198: if ($scope eq 'public') {
7199: if ($start <= $now && $end == 0) {
7200: $action = 'none';
7201: } else {
7202: $action = 'update';
7203: $aclnum = $num;
7204: }
7205: last;
7206: }
7207: }
7208: if ($action eq 'none') {
7209: return 'ok';
7210: } else {
7211: my %changes;
7212: my $newend = 0;
7213: my $newstart = $now;
7214: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7215: $changes{$action}{$newkey} = {
7216: type => 'public',
7217: time => {
7218: start => $newstart,
7219: end => $newend,
7220: },
7221: };
7222: my ($outcome,$deloutcome,$new_values,$translation) =
7223: &modify_access_controls($file_name,\%changes,$udom,$unum);
7224: return $outcome;
7225: }
7226: } else {
7227: return 'invalid';
7228: }
7229: }
7230:
1.745 raeburn 7231: #------------------------------------------------------Get Marked as Read Only
7232:
7233: sub get_marked_as_readonly {
7234: my ($domain,$user,$what,$group) = @_;
7235: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7236: my @readonly_files;
1.629 banghart 7237: my $cmp1=$what;
7238: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7239: while (my ($file_name,$value) = each(%{$current_permissions})) {
7240: if (defined($group)) {
7241: if ($file_name !~ m-^\Q$group\E/-) {
7242: next;
7243: }
7244: }
1.561 banghart 7245: if (ref($value) eq "ARRAY"){
7246: foreach my $stored_what (@{$value}) {
1.629 banghart 7247: my $cmp2=$stored_what;
1.759 albertel 7248: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7249: $cmp2=join('',@{$stored_what});
1.745 raeburn 7250: }
1.629 banghart 7251: if ($cmp1 eq $cmp2) {
1.561 banghart 7252: push(@readonly_files, $file_name);
1.745 raeburn 7253: last;
1.563 banghart 7254: } elsif (!defined($what)) {
7255: push(@readonly_files, $file_name);
1.745 raeburn 7256: last;
1.561 banghart 7257: }
7258: }
1.745 raeburn 7259: }
1.561 banghart 7260: }
7261: return @readonly_files;
7262: }
1.577 banghart 7263: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7264:
1.577 banghart 7265: sub get_marked_as_readonly_hash {
1.745 raeburn 7266: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7267: my %readonly_files;
1.745 raeburn 7268: while (my ($file_name,$value) = each(%{$current_permissions})) {
7269: if (defined($group)) {
7270: if ($file_name !~ m-^\Q$group\E/-) {
7271: next;
7272: }
7273: }
1.577 banghart 7274: if (ref($value) eq "ARRAY"){
7275: foreach my $stored_what (@{$value}) {
1.745 raeburn 7276: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7277: foreach my $lock_descriptor(@{$stored_what}) {
7278: if ($lock_descriptor eq 'graded') {
7279: $readonly_files{$file_name} = 'graded';
7280: } elsif ($lock_descriptor eq 'handback') {
7281: $readonly_files{$file_name} = 'handback';
7282: } else {
7283: if (!exists($readonly_files{$file_name})) {
7284: $readonly_files{$file_name} = 'locked';
7285: }
7286: }
1.745 raeburn 7287: }
1.750 banghart 7288: }
1.577 banghart 7289: }
7290: }
7291: }
7292: return %readonly_files;
7293: }
1.559 banghart 7294: # ------------------------------------------------------------ Unmark as Read Only
7295:
7296: sub unmark_as_readonly {
1.629 banghart 7297: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7298: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7299: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7300: $file_name = &declutter_portfile($file_name);
1.634 albertel 7301: my $symb_crs = $what;
7302: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7303: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7304: my ($tmp)=keys(%current_permissions);
7305: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7306: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7307: foreach my $file (@readonly_files) {
1.759 albertel 7308: my $clean_file = &declutter_portfile($file);
7309: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7310: my $current_locks = $current_permissions{$file};
1.563 banghart 7311: my @new_locks;
7312: my @del_keys;
7313: if (ref($current_locks) eq "ARRAY"){
7314: foreach my $locker (@{$current_locks}) {
1.632 albertel 7315: my $compare=$locker;
1.749 raeburn 7316: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7317: $compare=join('',@{$locker});
1.746 raeburn 7318: if ($compare ne $symb_crs) {
7319: push(@new_locks, $locker);
7320: }
1.563 banghart 7321: }
7322: }
1.650 albertel 7323: if (scalar(@new_locks) > 0) {
1.563 banghart 7324: $current_permissions{$file} = \@new_locks;
7325: } else {
7326: push(@del_keys, $file);
1.613 albertel 7327: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7328: delete($current_permissions{$file});
1.563 banghart 7329: }
7330: }
1.561 banghart 7331: }
1.613 albertel 7332: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7333: return;
7334: }
1.512 banghart 7335:
1.17 www 7336: # ------------------------------------------------------------ Directory lister
7337:
7338: sub dirlist {
1.955 raeburn 7339: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7340: $uri=~s/^\///;
7341: $uri=~s/\/$//;
1.253 stredwic 7342: my ($udom, $uname);
1.955 raeburn 7343: if ($getuserdir) {
1.253 stredwic 7344: $udom = $userdomain;
7345: $uname = $username;
1.955 raeburn 7346: } else {
7347: (undef,$udom,$uname)=split(/\//,$uri);
7348: if(defined($userdomain)) {
7349: $udom = $userdomain;
7350: }
7351: if(defined($username)) {
7352: $uname = $username;
7353: }
1.253 stredwic 7354: }
1.955 raeburn 7355: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7356:
1.955 raeburn 7357: $dirRoot = $perlvar{'lonDocRoot'};
7358: if (defined($getpropath)) {
7359: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7360: $dirRoot =~ s/\/$//;
1.955 raeburn 7361: } elsif (defined($getuserdir)) {
7362: my $subdir=$uname.'__';
7363: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7364: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7365: ."/$udom/$subdir/$uname";
7366: } elsif (defined($alternateRoot)) {
7367: $dirRoot = $alternateRoot;
1.751 banghart 7368: }
1.253 stredwic 7369:
7370: if($udom) {
7371: if($uname) {
1.955 raeburn 7372: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7373: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7374: .':'.&escape($uname).':'.&escape($udom),
7375: &homeserver($uname,$udom));
7376: if ($listing eq 'unknown_cmd') {
7377: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7378: &homeserver($uname,$udom));
7379: } else {
7380: @listing_results = map { &unescape($_); } split(/:/,$listing);
7381: }
1.605 matthew 7382: if ($listing eq 'unknown_cmd') {
1.800 albertel 7383: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7384: &homeserver($uname,$udom));
1.605 matthew 7385: @listing_results = split(/:/,$listing);
7386: } else {
7387: @listing_results = map { &unescape($_); } split(/:/,$listing);
7388: }
7389: return @listing_results;
1.955 raeburn 7390: } elsif(!$alternateRoot) {
1.800 albertel 7391: my %allusers;
1.841 albertel 7392: my %servers = &get_servers($udom,'library');
1.955 raeburn 7393: foreach my $tryserver (keys(%servers)) {
7394: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7395: &escape($udom),$tryserver);
7396: if ($listing eq 'unknown_cmd') {
7397: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7398: $udom, $tryserver);
7399: } else {
7400: @listing_results = map { &unescape($_); } split(/:/,$listing);
7401: }
1.841 albertel 7402: if ($listing eq 'unknown_cmd') {
7403: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7404: $udom, $tryserver);
7405: @listing_results = split(/:/,$listing);
7406: } else {
7407: @listing_results =
7408: map { &unescape($_); } split(/:/,$listing);
7409: }
7410: if ($listing_results[0] ne 'no_such_dir' &&
7411: $listing_results[0] ne 'empty' &&
7412: $listing_results[0] ne 'con_lost') {
7413: foreach my $line (@listing_results) {
7414: my ($entry) = split(/&/,$line,2);
7415: $allusers{$entry} = 1;
7416: }
7417: }
1.253 stredwic 7418: }
7419: my $alluserstr='';
1.800 albertel 7420: foreach my $user (sort(keys(%allusers))) {
7421: $alluserstr.=$user.'&user:';
1.253 stredwic 7422: }
7423: $alluserstr=~s/:$//;
7424: return split(/:/,$alluserstr);
7425: } else {
1.800 albertel 7426: return ('missing user name');
1.253 stredwic 7427: }
1.955 raeburn 7428: } elsif(!defined($getpropath)) {
1.841 albertel 7429: my @all_domains = sort(&all_domains());
1.955 raeburn 7430: foreach my $domain (@all_domains) {
7431: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7432: }
7433: return @all_domains;
7434: } else {
1.800 albertel 7435: return ('missing domain');
1.275 stredwic 7436: }
7437: }
7438:
7439: # --------------------------------------------- GetFileTimestamp
7440: # This function utilizes dirlist and returns the date stamp for
7441: # when it was last modified. It will also return an error of -1
7442: # if an error occurs
7443:
7444: sub GetFileTimestamp {
1.955 raeburn 7445: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7446: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7447: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7448: my ($fileStat) =
7449: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7450: undef,$getuserdir);
1.275 stredwic 7451: my @stats = split('&', $fileStat);
7452: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7453: # @stats contains first the filename, then the stat output
7454: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7455: } else {
7456: return -1;
1.253 stredwic 7457: }
1.26 www 7458: }
7459:
1.712 albertel 7460: sub stat_file {
7461: my ($uri) = @_;
1.787 albertel 7462: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7463:
1.955 raeburn 7464: my ($udom,$uname,$file);
1.712 albertel 7465: if ($uri =~ m-^/(uploaded|editupload)/-) {
7466: ($udom,$uname,$file) =
1.811 albertel 7467: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7468: $file = 'userfiles/'.$file;
7469: }
7470: if ($uri =~ m-^/res/-) {
7471: ($udom,$uname) =
1.807 albertel 7472: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7473: $file = $uri;
7474: }
7475:
7476: if (!$udom || !$uname || !$file) {
7477: # unable to handle the uri
7478: return ();
7479: }
1.956 raeburn 7480: my $getpropath;
7481: if ($file =~ /^userfiles\//) {
7482: $getpropath = 1;
7483: }
1.955 raeburn 7484: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7485: my @stats = split('&', $result);
1.721 banghart 7486:
1.712 albertel 7487: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7488: shift(@stats); #filename is first
7489: return @stats;
7490: }
7491: return ();
7492: }
7493:
1.26 www 7494: # -------------------------------------------------------- Value of a Condition
7495:
1.713 albertel 7496: # gets the value of a specific preevaluated condition
7497: # stored in the string $env{user.state.<cid>}
7498: # or looks up a condition reference in the bighash and if if hasn't
7499: # already been evaluated recurses into docondval to get the value of
7500: # the condition, then memoizing it to
7501: # $env{user.state.<cid>.<condition>}
1.40 www 7502: sub directcondval {
7503: my $number=shift;
1.620 albertel 7504: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7505: &Apache::lonuserstate::evalstate();
7506: }
1.713 albertel 7507: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7508: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7509: } elsif ($number =~ /^_/) {
7510: my $sub_condition;
7511: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7512: &GDBM_READER(),0640)) {
7513: $sub_condition=$bighash{'conditions'.$number};
7514: untie(%bighash);
7515: }
7516: my $value = &docondval($sub_condition);
1.949 raeburn 7517: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7518: return $value;
7519: }
1.620 albertel 7520: if ($env{'user.state.'.$env{'request.course.id'}}) {
7521: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7522: } else {
7523: return 2;
7524: }
7525: }
7526:
1.713 albertel 7527: # get the collection of conditions for this resource
1.26 www 7528: sub condval {
7529: my $condidx=shift;
1.54 www 7530: my $allpathcond='';
1.713 albertel 7531: foreach my $cond (split(/\|/,$condidx)) {
7532: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7533: $allpathcond.=
7534: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7535: }
1.191 harris41 7536: }
1.54 www 7537: $allpathcond=~s/\|$//;
1.713 albertel 7538: return &docondval($allpathcond);
7539: }
7540:
7541: #evaluates an expression of conditions
7542: sub docondval {
7543: my ($allpathcond) = @_;
7544: my $result=0;
7545: if ($env{'request.course.id'}
7546: && defined($allpathcond)) {
7547: my $operand='|';
7548: my @stack;
7549: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7550: if ($chunk eq '(') {
7551: push @stack,($operand,$result);
7552: } elsif ($chunk eq ')') {
7553: my $before=pop @stack;
7554: if (pop @stack eq '&') {
7555: $result=$result>$before?$before:$result;
7556: } else {
7557: $result=$result>$before?$result:$before;
7558: }
7559: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7560: $operand=$chunk;
7561: } else {
7562: my $new=directcondval($chunk);
7563: if ($operand eq '&') {
7564: $result=$result>$new?$new:$result;
7565: } else {
7566: $result=$result>$new?$result:$new;
7567: }
7568: }
7569: }
1.26 www 7570: }
7571: return $result;
1.421 albertel 7572: }
7573:
7574: # ---------------------------------------------------- Devalidate courseresdata
7575:
7576: sub devalidatecourseresdata {
7577: my ($coursenum,$coursedomain)=@_;
7578: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7579: &devalidate_cache_new('courseres',$hashid);
1.28 www 7580: }
7581:
1.763 www 7582:
1.200 www 7583: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7584: #
7585: # Parameters:
7586: # $coursenum - Number of the course.
7587: # $coursedomain - Domain at which the course was created.
7588: # Returns:
7589: # A hash of the course parameters along (I think) with timestamps
7590: # and version info.
1.877 foxr 7591:
1.624 albertel 7592: sub get_courseresdata {
7593: my ($coursenum,$coursedomain)=@_;
1.200 www 7594: my $coursehom=&homeserver($coursenum,$coursedomain);
7595: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7596: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7597: my %dumpreply;
1.417 albertel 7598: unless (defined($cached)) {
1.624 albertel 7599: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7600: $result=\%dumpreply;
1.251 albertel 7601: my ($tmp) = keys(%dumpreply);
7602: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7603: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7604: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7605: return $tmp;
1.416 albertel 7606: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7607: $result=undef;
1.599 albertel 7608: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7609: }
7610: }
1.624 albertel 7611: return $result;
7612: }
7613:
1.633 albertel 7614: sub devalidateuserresdata {
7615: my ($uname,$udom)=@_;
7616: my $hashid="$udom:$uname";
7617: &devalidate_cache_new('userres',$hashid);
7618: }
7619:
1.624 albertel 7620: sub get_userresdata {
7621: my ($uname,$udom)=@_;
7622: #most student don\'t have any data set, check if there is some data
7623: if (&EXT_cache_status($udom,$uname)) { return undef; }
7624:
7625: my $hashid="$udom:$uname";
7626: my ($result,$cached)=&is_cached_new('userres',$hashid);
7627: if (!defined($cached)) {
7628: my %resourcedata=&dump('resourcedata',$udom,$uname);
7629: $result=\%resourcedata;
7630: &do_cache_new('userres',$hashid,$result,600);
7631: }
7632: my ($tmp)=keys(%$result);
7633: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7634: return $result;
7635: }
7636: #error 2 occurs when the .db doesn't exist
7637: if ($tmp!~/error: 2 /) {
1.672 albertel 7638: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7639: " Trying to get resource data for ".
7640: $uname." at ".$udom.": ".
7641: $tmp."</font>");
7642: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7643: #&EXT_cache_set($udom,$uname);
7644: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7645: undef($tmp); # not really an error so don't send it back
1.624 albertel 7646: }
7647: return $tmp;
7648: }
1.879 foxr 7649: #----------------------------------------------- resdata - return resource data
7650: # Purpose:
7651: # Return resource data for either users or for a course.
7652: # Parameters:
7653: # $name - Course/user name.
7654: # $domain - Name of the domain the user/course is registered on.
7655: # $type - Type of thing $name is (must be 'course' or 'user'
7656: # @which - Array of names of resources desired.
7657: # Returns:
7658: # The value of the first reasource in @which that is found in the
7659: # resource hash.
7660: # Exceptional Conditions:
7661: # If the $type passed in is not valid (not the string 'course' or
7662: # 'user', an undefined reference is returned.
7663: # If none of the resources are found, an undef is returned
1.624 albertel 7664: sub resdata {
7665: my ($name,$domain,$type,@which)=@_;
7666: my $result;
7667: if ($type eq 'course') {
7668: $result=&get_courseresdata($name,$domain);
7669: } elsif ($type eq 'user') {
7670: $result=&get_userresdata($name,$domain);
7671: }
7672: if (!ref($result)) { return $result; }
1.251 albertel 7673: foreach my $item (@which) {
1.927 albertel 7674: if (defined($result->{$item->[0]})) {
7675: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7676: }
1.250 albertel 7677: }
1.291 albertel 7678: return undef;
1.200 www 7679: }
7680:
1.379 matthew 7681: #
7682: # EXT resource caching routines
7683: #
7684:
7685: sub clear_EXT_cache_status {
1.383 albertel 7686: &delenv('cache.EXT.');
1.379 matthew 7687: }
7688:
7689: sub EXT_cache_status {
7690: my ($target_domain,$target_user) = @_;
1.383 albertel 7691: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7692: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7693: # We know already the user has no data
7694: return 1;
7695: } else {
7696: return 0;
7697: }
7698: }
7699:
7700: sub EXT_cache_set {
7701: my ($target_domain,$target_user) = @_;
1.383 albertel 7702: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7703: #&appenv({$cachename => time});
1.379 matthew 7704: }
7705:
1.28 www 7706: # --------------------------------------------------------- Value of a Variable
1.58 www 7707: sub EXT {
1.715 albertel 7708:
1.395 albertel 7709: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7710: unless ($varname) { return ''; }
1.218 albertel 7711: #get real user name/domain, courseid and symb
7712: my $courseid;
1.359 albertel 7713: my $publicuser;
1.427 www 7714: if ($symbparm) {
7715: $symbparm=&get_symb_from_alias($symbparm);
7716: }
1.218 albertel 7717: if (!($uname && $udom)) {
1.790 albertel 7718: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7719: if (!$symbparm) { $symbparm=$cursymb; }
7720: } else {
1.620 albertel 7721: $courseid=$env{'request.course.id'};
1.218 albertel 7722: }
1.48 www 7723: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7724: my $rest;
1.320 albertel 7725: if (defined($therest[0])) {
1.48 www 7726: $rest=join('.',@therest);
7727: } else {
7728: $rest='';
7729: }
1.320 albertel 7730:
1.57 www 7731: my $qualifierrest=$qualifier;
7732: if ($rest) { $qualifierrest.='.'.$rest; }
7733: my $spacequalifierrest=$space;
7734: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7735: if ($realm eq 'user') {
1.48 www 7736: # --------------------------------------------------------------- user.resource
7737: if ($space eq 'resource') {
1.651 albertel 7738: if ( (defined($Apache::lonhomework::parsing_a_problem)
7739: || defined($Apache::lonhomework::parsing_a_task))
7740: &&
1.744 albertel 7741: ($symbparm eq &symbread()) ) {
7742: # if we are in the middle of processing the resource the
7743: # get the value we are planning on committing
7744: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7745: return $Apache::lonhomework::results{$qualifierrest};
7746: } else {
7747: return $Apache::lonhomework::history{$qualifierrest};
7748: }
1.335 albertel 7749: } else {
1.359 albertel 7750: my %restored;
1.620 albertel 7751: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7752: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7753: } else {
7754: %restored=&restore($symbparm,$courseid,$udom,$uname);
7755: }
1.335 albertel 7756: return $restored{$qualifierrest};
7757: }
1.48 www 7758: # ----------------------------------------------------------------- user.access
7759: } elsif ($space eq 'access') {
1.218 albertel 7760: # FIXME - not supporting calls for a specific user
1.48 www 7761: return &allowed($qualifier,$rest);
7762: # ------------------------------------------ user.preferences, user.environment
7763: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7764: if (($uname eq $env{'user.name'}) &&
7765: ($udom eq $env{'user.domain'})) {
7766: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7767: } else {
1.359 albertel 7768: my %returnhash;
7769: if (!$publicuser) {
7770: %returnhash=&userenvironment($udom,$uname,
7771: $qualifierrest);
7772: }
1.218 albertel 7773: return $returnhash{$qualifierrest};
7774: }
1.48 www 7775: # ----------------------------------------------------------------- user.course
7776: } elsif ($space eq 'course') {
1.218 albertel 7777: # FIXME - not supporting calls for a specific user
1.620 albertel 7778: return $env{join('.',('request.course',$qualifier))};
1.48 www 7779: # ------------------------------------------------------------------- user.role
7780: } elsif ($space eq 'role') {
1.218 albertel 7781: # FIXME - not supporting calls for a specific user
1.620 albertel 7782: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7783: if ($qualifier eq 'value') {
7784: return $role;
7785: } elsif ($qualifier eq 'extent') {
7786: return $where;
7787: }
7788: # ----------------------------------------------------------------- user.domain
7789: } elsif ($space eq 'domain') {
1.218 albertel 7790: return $udom;
1.48 www 7791: # ------------------------------------------------------------------- user.name
7792: } elsif ($space eq 'name') {
1.218 albertel 7793: return $uname;
1.48 www 7794: # ---------------------------------------------------- Any other user namespace
1.29 www 7795: } else {
1.359 albertel 7796: my %reply;
7797: if (!$publicuser) {
7798: %reply=&get($space,[$qualifierrest],$udom,$uname);
7799: }
7800: return $reply{$qualifierrest};
1.48 www 7801: }
1.236 www 7802: } elsif ($realm eq 'query') {
7803: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7804: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7805: [$spacequalifierrest]);
1.620 albertel 7806: return $env{'form.'.$spacequalifierrest};
1.236 www 7807: } elsif ($realm eq 'request') {
1.48 www 7808: # ------------------------------------------------------------- request.browser
7809: if ($space eq 'browser') {
1.430 www 7810: if ($qualifier eq 'textremote') {
1.676 albertel 7811: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7812: return 1;
7813: } else {
7814: return 0;
7815: }
7816: } else {
1.620 albertel 7817: return $env{'browser.'.$qualifier};
1.430 www 7818: }
1.57 www 7819: # ------------------------------------------------------------ request.filename
7820: } else {
1.620 albertel 7821: return $env{'request.'.$spacequalifierrest};
1.29 www 7822: }
1.28 www 7823: } elsif ($realm eq 'course') {
1.48 www 7824: # ---------------------------------------------------------- course.description
1.620 albertel 7825: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7826: } elsif ($realm eq 'resource') {
1.165 www 7827:
1.620 albertel 7828: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7829: if (!$symbparm) { $symbparm=&symbread(); }
7830: }
1.693 albertel 7831:
7832: if ($space eq 'title') {
7833: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7834: return &gettitle($symbparm);
7835: }
7836:
7837: if ($space eq 'map') {
7838: my ($map) = &decode_symb($symbparm);
7839: return &symbread($map);
7840: }
1.905 albertel 7841: if ($space eq 'filename') {
7842: if ($symbparm) {
7843: return &clutter((&decode_symb($symbparm))[2]);
7844: }
7845: return &hreflocation('',$env{'request.filename'});
7846: }
1.693 albertel 7847:
7848: my ($section, $group, @groups);
1.593 albertel 7849: my ($courselevelm,$courselevel);
1.539 albertel 7850: if ($symbparm && defined($courseid) &&
1.620 albertel 7851: $courseid eq $env{'request.course.id'}) {
1.165 www 7852:
1.218 albertel 7853: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7854:
1.60 www 7855: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7856: my $symbp=$symbparm;
1.735 albertel 7857: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7858:
7859: my $symbparm=$symbp.'.'.$spacequalifierrest;
7860: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7861:
1.620 albertel 7862: if (($env{'user.name'} eq $uname) &&
7863: ($env{'user.domain'} eq $udom)) {
7864: $section=$env{'request.course.sec'};
1.733 raeburn 7865: @groups = split(/:/,$env{'request.course.groups'});
7866: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7867: } else {
1.539 albertel 7868: if (! defined($usection)) {
1.551 albertel 7869: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7870: } else {
7871: $section = $usection;
7872: }
1.733 raeburn 7873: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7874: }
7875:
7876: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7877: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7878: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7879:
1.593 albertel 7880: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7881: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7882: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7883:
1.60 www 7884: # ----------------------------------------------------------- first, check user
1.624 albertel 7885:
7886: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7887: ([$courselevelr,'resource'],
7888: [$courselevelm,'map' ],
7889: [$courselevel, 'course' ]));
1.931 albertel 7890: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7891:
1.594 albertel 7892: # ------------------------------------------------ second, check some of course
1.684 raeburn 7893: my $coursereply;
1.691 raeburn 7894: if (@groups > 0) {
7895: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7896: $mapparm,$spacequalifierrest);
1.927 albertel 7897: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7898: }
1.96 www 7899:
1.684 raeburn 7900: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7901: $env{'course.'.$courseid.'.domain'},
7902: 'course',
7903: ([$seclevelr, 'resource'],
7904: [$seclevelm, 'map' ],
7905: [$seclevel, 'course' ],
7906: [$courselevelr,'resource']));
7907: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7908:
1.60 www 7909: # ------------------------------------------------------ third, check map parms
1.218 albertel 7910: my %parmhash=();
7911: my $thisparm='';
7912: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7913: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7914: &GDBM_READER(),0640)) {
1.218 albertel 7915: $thisparm=$parmhash{$symbparm};
7916: untie(%parmhash);
7917: }
1.927 albertel 7918: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7919: }
1.594 albertel 7920: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7921:
1.218 albertel 7922: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7923: my $filename;
7924: if (!$symbparm) { $symbparm=&symbread(); }
7925: if ($symbparm) {
1.409 www 7926: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7927: } else {
1.620 albertel 7928: $filename=$env{'request.filename'};
1.282 albertel 7929: }
7930: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7931: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7932: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7933: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7934:
1.927 albertel 7935: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7936: if ($symbparm && defined($courseid) &&
1.620 albertel 7937: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7938: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7939: $env{'course.'.$courseid.'.domain'},
7940: 'course',
1.927 albertel 7941: ([$courselevelm,'map' ],
7942: [$courselevel, 'course']));
7943: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7944: }
1.145 www 7945: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7946: unless ($space eq '0') {
1.336 albertel 7947: my @parts=split(/_/,$space);
7948: my $id=pop(@parts);
7949: my $part=join('_',@parts);
7950: if ($part eq '') { $part='0'; }
1.927 albertel 7951: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7952: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7953: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7954: }
1.395 albertel 7955: if ($recurse) { return undef; }
7956: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7957: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7958: # ---------------------------------------------------- Any other user namespace
7959: } elsif ($realm eq 'environment') {
7960: # ----------------------------------------------------------------- environment
1.620 albertel 7961: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7962: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7963: } else {
1.770 albertel 7964: if ($uname eq 'anonymous' && $udom eq '') {
7965: return '';
7966: }
1.219 albertel 7967: my %returnhash=&userenvironment($udom,$uname,
7968: $spacequalifierrest);
7969: return $returnhash{$spacequalifierrest};
7970: }
1.28 www 7971: } elsif ($realm eq 'system') {
1.48 www 7972: # ----------------------------------------------------------------- system.time
7973: if ($space eq 'time') {
7974: return time;
7975: }
1.696 albertel 7976: } elsif ($realm eq 'server') {
7977: # ----------------------------------------------------------------- system.time
7978: if ($space eq 'name') {
7979: return $ENV{'SERVER_NAME'};
7980: }
1.28 www 7981: }
1.48 www 7982: return '';
1.61 www 7983: }
7984:
1.927 albertel 7985: sub get_reply {
7986: my ($reply_value) = @_;
1.940 raeburn 7987: if (ref($reply_value) eq 'ARRAY') {
7988: if (wantarray) {
7989: return @$reply_value;
7990: }
7991: return $reply_value->[0];
7992: } else {
7993: return $reply_value;
1.927 albertel 7994: }
7995: }
7996:
1.691 raeburn 7997: sub check_group_parms {
7998: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7999: my @groupitems = ();
8000: my $resultitem;
1.927 albertel 8001: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8002: foreach my $group (@{$groups}) {
8003: foreach my $level (@levels) {
1.927 albertel 8004: my $item = $courseid.'.['.$group.'].'.$level->[0];
8005: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8006: }
8007: }
8008: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8009: $env{'course.'.$courseid.'.domain'},
8010: 'course',@groupitems);
8011: return $coursereply;
8012: }
8013:
8014: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8015: my ($courseid,@groups) = @_;
8016: @groups = sort(@groups);
1.691 raeburn 8017: return @groups;
8018: }
8019:
1.395 albertel 8020: sub packages_tab_default {
8021: my ($uri,$varname)=@_;
8022: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8023:
8024: my (@extension,@specifics,$do_default);
8025: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8026: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8027: if ($pack_type eq 'default') {
8028: $do_default=1;
8029: } elsif ($pack_type eq 'extension') {
8030: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8031: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8032: # only look at packages defaults for packages that this id is
1.738 albertel 8033: push(@specifics,[$package,$pack_type,$pack_part]);
8034: }
8035: }
8036: # first look for a package that matches the requested part id
8037: foreach my $package (@specifics) {
8038: my (undef,$pack_type,$pack_part)=@{$package};
8039: next if ($pack_part ne $part);
8040: if (defined($packagetab{"$pack_type&$name&default"})) {
8041: return $packagetab{"$pack_type&$name&default"};
8042: }
8043: }
8044: # look for any possible matching non extension_ package
8045: foreach my $package (@specifics) {
8046: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8047: if (defined($packagetab{"$pack_type&$name&default"})) {
8048: return $packagetab{"$pack_type&$name&default"};
8049: }
1.585 albertel 8050: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8051: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8052: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8053: }
8054: }
1.738 albertel 8055: # look for any posible extension_ match
8056: foreach my $package (@extension) {
8057: my ($package,$pack_type)=@{$package};
8058: if (defined($packagetab{"$pack_type&$name&default"})) {
8059: return $packagetab{"$pack_type&$name&default"};
8060: }
8061: if (defined($packagetab{$package."&$name&default"})) {
8062: return $packagetab{$package."&$name&default"};
8063: }
8064: }
8065: # look for a global default setting
8066: if ($do_default && defined($packagetab{"default&$name&default"})) {
8067: return $packagetab{"default&$name&default"};
8068: }
1.395 albertel 8069: return undef;
8070: }
8071:
1.334 albertel 8072: sub add_prefix_and_part {
8073: my ($prefix,$part)=@_;
8074: my $keyroot;
8075: if (defined($prefix) && $prefix !~ /^__/) {
8076: # prefix that has a part already
8077: $keyroot=$prefix;
8078: } elsif (defined($prefix)) {
8079: # prefix that is missing a part
8080: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8081: } else {
8082: # no prefix at all
8083: if (defined($part)) { $keyroot='_'.$part; }
8084: }
8085: return $keyroot;
8086: }
8087:
1.71 www 8088: # ---------------------------------------------------------------- Get metadata
8089:
1.599 albertel 8090: my %metaentry;
1.71 www 8091: sub metadata {
1.176 www 8092: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8093: $uri=&declutter($uri);
1.288 albertel 8094: # if it is a non metadata possible uri return quickly
1.529 albertel 8095: if (($uri eq '') ||
8096: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8097: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8098: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8099: return undef;
8100: }
8101: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8102: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8103: return undef;
1.288 albertel 8104: }
1.73 www 8105: my $filename=$uri;
8106: $uri=~s/\.meta$//;
1.172 www 8107: #
8108: # Is the metadata already cached?
1.177 www 8109: # Look at timestamp of caching
1.172 www 8110: # Everything is cached by the main uri, libraries are never directly cached
8111: #
1.428 albertel 8112: if (!defined($liburi)) {
1.599 albertel 8113: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8114: if (defined($cached)) { return $result->{':'.$what}; }
8115: }
8116: {
1.172 www 8117: #
8118: # Is this a recursive call for a library?
8119: #
1.599 albertel 8120: # if (! exists($metacache{$uri})) {
8121: # $metacache{$uri}={};
8122: # }
1.924 albertel 8123: my $cachetime = 60*60;
1.171 www 8124: if ($liburi) {
8125: $liburi=&declutter($liburi);
8126: $filename=$liburi;
1.401 bowersj2 8127: } else {
1.599 albertel 8128: &devalidate_cache_new('meta',$uri);
8129: undef(%metaentry);
1.401 bowersj2 8130: }
1.140 www 8131: my %metathesekeys=();
1.73 www 8132: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8133: my $metastring;
1.924 albertel 8134: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8135: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8136: $metastring =
1.929 albertel 8137: &Apache::lonnet::ssi_body($which,
1.924 albertel 8138: ('grade_target' => 'meta'));
8139: $cachetime = 1; # only want this cached in the child not long term
8140: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8141: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8142: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8143: $metastring=&getfile($file);
1.489 albertel 8144: }
1.208 albertel 8145: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8146: my $token;
1.140 www 8147: undef %metathesekeys;
1.71 www 8148: while ($token=$parser->get_token) {
1.339 albertel 8149: if ($token->[0] eq 'S') {
8150: if (defined($token->[2]->{'package'})) {
1.172 www 8151: #
8152: # This is a package - get package info
8153: #
1.339 albertel 8154: my $package=$token->[2]->{'package'};
8155: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8156: if (defined($token->[2]->{'id'})) {
8157: $keyroot.='_'.$token->[2]->{'id'};
8158: }
1.599 albertel 8159: if ($metaentry{':packages'}) {
8160: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8161: } else {
1.599 albertel 8162: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8163: }
1.736 albertel 8164: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8165: my $part=$keyroot;
8166: $part=~s/^\_//;
1.736 albertel 8167: if ($pack_entry=~/^\Q$package\E\&/ ||
8168: $pack_entry=~/^\Q$package\E_0\&/) {
8169: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8170: # ignore package.tab specified default values
8171: # here &package_tab_default() will fetch those
8172: if ($subp eq 'default') { next; }
1.736 albertel 8173: my $value=$packagetab{$pack_entry};
1.432 albertel 8174: my $unikey;
8175: if ($pack =~ /_0$/) {
8176: $unikey='parameter_0_'.$name;
8177: $part=0;
8178: } else {
8179: $unikey='parameter'.$keyroot.'_'.$name;
8180: }
1.339 albertel 8181: if ($subp eq 'display') {
8182: $value.=' [Part: '.$part.']';
8183: }
1.599 albertel 8184: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8185: $metathesekeys{$unikey}=1;
1.599 albertel 8186: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8187: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8188: }
1.599 albertel 8189: if (defined($metaentry{':'.$unikey.'.default'})) {
8190: $metaentry{':'.$unikey}=
8191: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8192: }
1.339 albertel 8193: }
8194: }
8195: } else {
1.172 www 8196: #
8197: # This is not a package - some other kind of start tag
1.339 albertel 8198: #
8199: my $entry=$token->[1];
8200: my $unikey;
8201: if ($entry eq 'import') {
8202: $unikey='';
8203: } else {
8204: $unikey=$entry;
8205: }
8206: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8207:
8208: if (defined($token->[2]->{'id'})) {
8209: $unikey.='_'.$token->[2]->{'id'};
8210: }
1.175 www 8211:
1.339 albertel 8212: if ($entry eq 'import') {
1.175 www 8213: #
8214: # Importing a library here
1.339 albertel 8215: #
8216: if ($depthcount<20) {
8217: my $location=$parser->get_text('/import');
8218: my $dir=$filename;
8219: $dir=~s|[^/]*$||;
8220: $location=&filelocation($dir,$location);
1.736 albertel 8221: my $metadata =
8222: &metadata($uri,'keys', $location,$unikey,
8223: $depthcount+1);
8224: foreach my $meta (split(',',$metadata)) {
8225: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8226: $metathesekeys{$meta}=1;
1.339 albertel 8227: }
8228: }
8229: } else {
8230:
8231: if (defined($token->[2]->{'name'})) {
8232: $unikey.='_'.$token->[2]->{'name'};
8233: }
8234: $metathesekeys{$unikey}=1;
1.736 albertel 8235: foreach my $param (@{$token->[3]}) {
8236: $metaentry{':'.$unikey.'.'.$param} =
8237: $token->[2]->{$param};
1.339 albertel 8238: }
8239: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8240: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8241: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8242: # only ws inside the tag, and not in default, so use default
8243: # as value
1.599 albertel 8244: $metaentry{':'.$unikey}=$default;
1.908 albertel 8245: } elsif ( $internaltext =~ /\S/ ) {
8246: # something interesting inside the tag
8247: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8248: } else {
1.908 albertel 8249: # no interesting values, don't set a default
1.339 albertel 8250: }
1.172 www 8251: # end of not-a-package not-a-library import
1.339 albertel 8252: }
1.172 www 8253: # end of not-a-package start tag
1.339 albertel 8254: }
1.172 www 8255: # the next is the end of "start tag"
1.339 albertel 8256: }
8257: }
1.483 albertel 8258: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8259: $extension = lc($extension);
8260: if ($extension eq 'htm') { $extension='html'; }
8261:
1.737 albertel 8262: foreach my $key (keys(%packagetab)) {
1.483 albertel 8263: #no specific packages #how's our extension
8264: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8265: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8266: \%metathesekeys);
8267: }
1.883 albertel 8268:
8269: if (!exists($metaentry{':packages'})
8270: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8271: foreach my $key (keys(%packagetab)) {
1.483 albertel 8272: #no specific packages well let's get default then
8273: if ($key!~/^default&/) { next; }
1.488 albertel 8274: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8275: \%metathesekeys);
8276: }
8277: }
1.338 www 8278: # are there custom rights to evaluate
1.599 albertel 8279: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8280:
1.338 www 8281: #
8282: # Importing a rights file here
1.339 albertel 8283: #
8284: unless ($depthcount) {
1.599 albertel 8285: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8286: my $dir=$filename;
8287: $dir=~s|[^/]*$||;
8288: $location=&filelocation($dir,$location);
1.736 albertel 8289: my $rights_metadata =
8290: &metadata($uri,'keys',$location,'_rights',
8291: $depthcount+1);
8292: foreach my $rights (split(',',$rights_metadata)) {
8293: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8294: $metathesekeys{$rights}=1;
1.339 albertel 8295: }
8296: }
8297: }
1.737 albertel 8298: # uniqifiy package listing
8299: my %seen;
8300: my @uniq_packages =
8301: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8302: $metaentry{':packages'} = join(',',@uniq_packages);
8303:
8304: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8305: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8306: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8307: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8308: # this is the end of "was not already recently cached
1.71 www 8309: }
1.599 albertel 8310: return $metaentry{':'.$what};
1.261 albertel 8311: }
8312:
1.488 albertel 8313: sub metadata_create_package_def {
1.483 albertel 8314: my ($uri,$key,$package,$metathesekeys)=@_;
8315: my ($pack,$name,$subp)=split(/\&/,$key);
8316: if ($subp eq 'default') { next; }
8317:
1.599 albertel 8318: if (defined($metaentry{':packages'})) {
8319: $metaentry{':packages'}.=','.$package;
1.483 albertel 8320: } else {
1.599 albertel 8321: $metaentry{':packages'}=$package;
1.483 albertel 8322: }
8323: my $value=$packagetab{$key};
8324: my $unikey;
8325: $unikey='parameter_0_'.$name;
1.599 albertel 8326: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8327: $$metathesekeys{$unikey}=1;
1.599 albertel 8328: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8329: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8330: }
1.599 albertel 8331: if (defined($metaentry{':'.$unikey.'.default'})) {
8332: $metaentry{':'.$unikey}=
8333: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8334: }
8335: }
8336:
1.261 albertel 8337: sub metadata_generate_part0 {
8338: my ($metadata,$metacache,$uri) = @_;
8339: my %allnames;
1.737 albertel 8340: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8341: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8342: my $part=$$metacache{':'.$metakey.'.part'};
8343: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8344: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8345: $allnames{$name}=$part;
8346: }
8347: }
8348: }
8349: foreach my $name (keys(%allnames)) {
8350: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8351: my $key=":parameter_0_$name";
1.261 albertel 8352: $$metacache{"$key.part"}='0';
8353: $$metacache{"$key.name"}=$name;
1.428 albertel 8354: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8355: $allnames{$name}.'_'.$name.
8356: '.type'};
1.428 albertel 8357: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8358: '.display'};
1.644 www 8359: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8360: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8361: $$metacache{"$key.display"}=$olddis;
8362: }
1.71 www 8363: }
8364:
1.764 albertel 8365: # ------------------------------------------------------ Devalidate title cache
8366:
8367: sub devalidate_title_cache {
8368: my ($url)=@_;
8369: if (!$env{'request.course.id'}) { return; }
8370: my $symb=&symbread($url);
8371: if (!$symb) { return; }
8372: my $key=$env{'request.course.id'}."\0".$symb;
8373: &devalidate_cache_new('title',$key);
8374: }
8375:
1.1014 droeschl 8376: # ------------------------------------------------- Get the title of a course
8377:
8378: sub current_course_title {
8379: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8380: }
1.301 www 8381: # ------------------------------------------------- Get the title of a resource
8382:
8383: sub gettitle {
8384: my $urlsymb=shift;
8385: my $symb=&symbread($urlsymb);
1.534 albertel 8386: if ($symb) {
1.620 albertel 8387: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8388: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8389: if (defined($cached)) {
8390: return $result;
8391: }
1.534 albertel 8392: my ($map,$resid,$url)=&decode_symb($symb);
8393: my $title='';
1.907 albertel 8394: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8395: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8396: } else {
8397: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8398: &GDBM_READER(),0640)) {
8399: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8400: $title=$bighash{'title_'.$mapid.'.'.$resid};
8401: untie(%bighash);
8402: }
1.534 albertel 8403: }
8404: $title=~s/\&colon\;/\:/gs;
8405: if ($title) {
1.599 albertel 8406: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8407: }
8408: $urlsymb=$url;
8409: }
8410: my $title=&metadata($urlsymb,'title');
8411: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8412: return $title;
1.301 www 8413: }
1.613 albertel 8414:
1.614 albertel 8415: sub get_slot {
8416: my ($which,$cnum,$cdom)=@_;
8417: if (!$cnum || !$cdom) {
1.790 albertel 8418: (undef,my $courseid)=&whichuser();
1.620 albertel 8419: $cdom=$env{'course.'.$courseid.'.domain'};
8420: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8421: }
1.703 albertel 8422: my $key=join("\0",'slots',$cdom,$cnum,$which);
8423: my %slotinfo;
8424: if (exists($remembered{$key})) {
8425: $slotinfo{$which} = $remembered{$key};
8426: } else {
8427: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8428: &Apache::lonhomework::showhash(%slotinfo);
8429: my ($tmp)=keys(%slotinfo);
8430: if ($tmp=~/^error:/) { return (); }
8431: $remembered{$key} = $slotinfo{$which};
8432: }
1.616 albertel 8433: if (ref($slotinfo{$which}) eq 'HASH') {
8434: return %{$slotinfo{$which}};
8435: }
8436: return $slotinfo{$which};
1.614 albertel 8437: }
1.31 www 8438: # ------------------------------------------------- Update symbolic store links
8439:
8440: sub symblist {
8441: my ($mapname,%newhash)=@_;
1.438 www 8442: $mapname=&deversion(&declutter($mapname));
1.31 www 8443: my %hash;
1.620 albertel 8444: if (($env{'request.course.fn'}) && (%newhash)) {
8445: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8446: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8447: foreach my $url (keys(%newhash)) {
1.711 albertel 8448: next if ($url eq 'last_known'
8449: && $env{'form.no_update_last_known'});
8450: $hash{declutter($url)}=&encode_symb($mapname,
8451: $newhash{$url}->[1],
8452: $newhash{$url}->[0]);
1.191 harris41 8453: }
1.31 www 8454: if (untie(%hash)) {
8455: return 'ok';
8456: }
8457: }
8458: }
8459: return 'error';
1.212 www 8460: }
8461:
8462: # --------------------------------------------------------------- Verify a symb
8463:
8464: sub symbverify {
1.510 www 8465: my ($symb,$thisurl)=@_;
8466: my $thisfn=$thisurl;
1.439 www 8467: $thisfn=&declutter($thisfn);
1.215 www 8468: # direct jump to resource in page or to a sequence - will construct own symbs
8469: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8470: # check URL part
1.409 www 8471: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8472:
1.431 www 8473: unless ($url eq $thisfn) { return 0; }
1.213 www 8474:
1.216 www 8475: $symb=&symbclean($symb);
1.510 www 8476: $thisurl=&deversion($thisurl);
1.439 www 8477: $thisfn=&deversion($thisfn);
1.213 www 8478:
8479: my %bighash;
8480: my $okay=0;
1.431 www 8481:
1.620 albertel 8482: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8483: &GDBM_READER(),0640)) {
1.1032 raeburn 8484: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8485: $thisurl =~ s/\?.+$//;
8486: }
1.510 www 8487: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8488: unless ($ids) {
1.510 www 8489: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8490: }
8491: if ($ids) {
8492: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8493: foreach my $id (split(/\,/,$ids)) {
8494: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8495: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8496: $symb =~ s/\?.+$//;
8497: }
1.216 www 8498: if (
8499: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8500: eq $symb) {
1.620 albertel 8501: if (($env{'request.role.adv'}) ||
1.800 albertel 8502: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8503: $okay=1;
8504: }
8505: }
1.216 www 8506: }
8507: }
1.213 www 8508: untie(%bighash);
8509: }
8510: return $okay;
1.31 www 8511: }
8512:
1.210 www 8513: # --------------------------------------------------------------- Clean-up symb
8514:
8515: sub symbclean {
8516: my $symb=shift;
1.568 albertel 8517: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8518: # remove version from map
8519: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8520:
1.210 www 8521: # remove version from URL
8522: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8523:
1.507 www 8524: # remove wrapper
8525:
1.510 www 8526: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8527: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8528: return $symb;
1.409 www 8529: }
8530:
8531: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8532:
8533: sub encode_symb {
8534: my ($map,$resid,$url)=@_;
8535: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8536: }
1.409 www 8537:
8538: sub decode_symb {
1.568 albertel 8539: my $symb=shift;
8540: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8541: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8542: return (&fixversion($map),$resid,&fixversion($url));
8543: }
8544:
8545: sub fixversion {
8546: my $fn=shift;
1.609 banghart 8547: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8548: my %bighash;
8549: my $uri=&clutter($fn);
1.620 albertel 8550: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8551: # is this cached?
1.599 albertel 8552: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8553: if (defined($cached)) { return $result; }
8554: # unfortunately not cached, or expired
1.620 albertel 8555: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8556: &GDBM_READER(),0640)) {
8557: if ($bighash{'version_'.$uri}) {
8558: my $version=$bighash{'version_'.$uri};
1.444 www 8559: unless (($version eq 'mostrecent') ||
8560: ($version==&getversion($uri))) {
1.440 www 8561: $uri=~s/\.(\w+)$/\.$version\.$1/;
8562: }
8563: }
8564: untie %bighash;
1.413 www 8565: }
1.599 albertel 8566: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8567: }
8568:
8569: sub deversion {
8570: my $url=shift;
8571: $url=~s/\.\d+\.(\w+)$/\.$1/;
8572: return $url;
1.210 www 8573: }
8574:
1.31 www 8575: # ------------------------------------------------------ Return symb list entry
8576:
8577: sub symbread {
1.249 www 8578: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8579: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8580: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8581: # no filename provided? try from environment
1.44 www 8582: unless ($thisfn) {
1.620 albertel 8583: if ($env{'request.symb'}) {
8584: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8585: }
1.620 albertel 8586: $thisfn=$env{'request.filename'};
1.44 www 8587: }
1.569 albertel 8588: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8589: # is that filename actually a symb? Verify, clean, and return
8590: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8591: if (&symbverify($thisfn,$1)) {
1.620 albertel 8592: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8593: }
1.242 www 8594: }
1.44 www 8595: $thisfn=declutter($thisfn);
1.31 www 8596: my %hash;
1.37 www 8597: my %bighash;
8598: my $syval='';
1.620 albertel 8599: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8600: my $targetfn = $thisfn;
1.609 banghart 8601: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8602: $targetfn = 'adm/wrapper/'.$thisfn;
8603: }
1.687 albertel 8604: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8605: $targetfn=$1;
8606: }
1.620 albertel 8607: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8608: &GDBM_READER(),0640)) {
1.481 raeburn 8609: $syval=$hash{$targetfn};
1.37 www 8610: untie(%hash);
8611: }
8612: # ---------------------------------------------------------- There was an entry
8613: if ($syval) {
1.601 albertel 8614: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8615: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8616: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8617: #return $env{$cache_str}='';
1.601 albertel 8618: #}
8619: #$syval.=$1;
8620: #}
1.37 www 8621: } else {
8622: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8623: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8624: &GDBM_READER(),0640)) {
1.37 www 8625: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8626: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8627: unless ($ids) {
8628: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8629: }
8630: unless ($ids) {
8631: # alias?
8632: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8633: }
1.37 www 8634: if ($ids) {
8635: # ------------------------------------------------------------------- Has ID(s)
8636: my @possibilities=split(/\,/,$ids);
1.39 www 8637: if ($#possibilities==0) {
8638: # ----------------------------------------------- There is only one possibility
1.37 www 8639: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8640: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8641: $resid,$thisfn);
1.249 www 8642: } elsif (!$donotrecurse) {
1.39 www 8643: # ------------------------------------------ There is more than one possibility
8644: my $realpossible=0;
1.800 albertel 8645: foreach my $id (@possibilities) {
8646: my $file=$bighash{'src_'.$id};
1.39 www 8647: if (&allowed('bre',$file)) {
1.800 albertel 8648: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8649: if ($bighash{'map_type_'.$mapid} ne 'page') {
8650: $realpossible++;
1.626 albertel 8651: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8652: $resid,$thisfn);
1.39 www 8653: }
8654: }
1.191 harris41 8655: }
1.39 www 8656: if ($realpossible!=1) { $syval=''; }
1.249 www 8657: } else {
8658: $syval='';
1.37 www 8659: }
8660: }
8661: untie(%bighash)
1.481 raeburn 8662: }
1.31 www 8663: }
1.62 www 8664: if ($syval) {
1.620 albertel 8665: return $env{$cache_str}=$syval;
1.62 www 8666: }
1.31 www 8667: }
1.949 raeburn 8668: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8669: return $env{$cache_str}='';
1.31 www 8670: }
8671:
8672: # ---------------------------------------------------------- Return random seed
8673:
1.32 www 8674: sub numval {
8675: my $txt=shift;
8676: $txt=~tr/A-J/0-9/;
8677: $txt=~tr/a-j/0-9/;
8678: $txt=~tr/K-T/0-9/;
8679: $txt=~tr/k-t/0-9/;
8680: $txt=~tr/U-Z/0-5/;
8681: $txt=~tr/u-z/0-5/;
8682: $txt=~s/\D//g;
1.564 albertel 8683: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8684: return int($txt);
1.368 albertel 8685: }
8686:
1.484 albertel 8687: sub numval2 {
8688: my $txt=shift;
8689: $txt=~tr/A-J/0-9/;
8690: $txt=~tr/a-j/0-9/;
8691: $txt=~tr/K-T/0-9/;
8692: $txt=~tr/k-t/0-9/;
8693: $txt=~tr/U-Z/0-5/;
8694: $txt=~tr/u-z/0-5/;
8695: $txt=~s/\D//g;
8696: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8697: my $total;
8698: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8699: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8700: return int($total);
8701: }
8702:
1.575 albertel 8703: sub numval3 {
8704: use integer;
8705: my $txt=shift;
8706: $txt=~tr/A-J/0-9/;
8707: $txt=~tr/a-j/0-9/;
8708: $txt=~tr/K-T/0-9/;
8709: $txt=~tr/k-t/0-9/;
8710: $txt=~tr/U-Z/0-5/;
8711: $txt=~tr/u-z/0-5/;
8712: $txt=~s/\D//g;
8713: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8714: my $total;
8715: foreach my $val (@txts) { $total+=$val; }
8716: if ($_64bit) { $total=(($total<<32)>>32); }
8717: return $total;
8718: }
8719:
1.675 albertel 8720: sub digest {
8721: my ($data)=@_;
8722: my $digest=&Digest::MD5::md5($data);
8723: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8724: my ($e,$f);
8725: {
8726: use integer;
8727: $e=($a+$b);
8728: $f=($c+$d);
8729: if ($_64bit) {
8730: $e=(($e<<32)>>32);
8731: $f=(($f<<32)>>32);
8732: }
8733: }
8734: if (wantarray) {
8735: return ($e,$f);
8736: } else {
8737: my $g;
8738: {
8739: use integer;
8740: $g=($e+$f);
8741: if ($_64bit) {
8742: $g=(($g<<32)>>32);
8743: }
8744: }
8745: return $g;
8746: }
8747: }
8748:
1.368 albertel 8749: sub latest_rnd_algorithm_id {
1.675 albertel 8750: return '64bit5';
1.366 albertel 8751: }
1.32 www 8752:
1.503 albertel 8753: sub get_rand_alg {
8754: my ($courseid)=@_;
1.790 albertel 8755: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8756: if ($courseid) {
1.620 albertel 8757: return $env{"course.$courseid.rndseed"};
1.503 albertel 8758: }
8759: return &latest_rnd_algorithm_id();
8760: }
8761:
1.562 albertel 8762: sub validCODE {
8763: my ($CODE)=@_;
8764: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8765: return 0;
8766: }
8767:
1.491 albertel 8768: sub getCODE {
1.620 albertel 8769: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8770: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8771: defined($Apache::lonhomework::parsing_a_task) ) &&
8772: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8773: return $Apache::lonhomework::history{'resource.CODE'};
8774: }
8775: return undef;
8776: }
8777:
1.31 www 8778: sub rndseed {
1.155 albertel 8779: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8780: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8781: if (!defined($symb)) {
1.366 albertel 8782: unless ($symb=$wsymb) { return time; }
8783: }
8784: if (!$courseid) { $courseid=$wcourseid; }
8785: if (!$domain) { $domain=$wdomain; }
8786: if (!$username) { $username=$wusername }
1.503 albertel 8787: my $which=&get_rand_alg();
1.803 albertel 8788:
1.491 albertel 8789: if (defined(&getCODE())) {
1.675 albertel 8790: if ($which eq '64bit5') {
8791: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8792: } elsif ($which eq '64bit4') {
1.575 albertel 8793: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8794: } else {
8795: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8796: }
1.675 albertel 8797: } elsif ($which eq '64bit5') {
8798: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8799: } elsif ($which eq '64bit4') {
8800: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8801: } elsif ($which eq '64bit3') {
8802: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8803: } elsif ($which eq '64bit2') {
8804: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8805: } elsif ($which eq '64bit') {
8806: return &rndseed_64bit($symb,$courseid,$domain,$username);
8807: }
8808: return &rndseed_32bit($symb,$courseid,$domain,$username);
8809: }
8810:
8811: sub rndseed_32bit {
8812: my ($symb,$courseid,$domain,$username)=@_;
8813: {
8814: use integer;
8815: my $symbchck=unpack("%32C*",$symb) << 27;
8816: my $symbseed=numval($symb) << 22;
8817: my $namechck=unpack("%32C*",$username) << 17;
8818: my $nameseed=numval($username) << 12;
8819: my $domainseed=unpack("%32C*",$domain) << 7;
8820: my $courseseed=unpack("%32C*",$courseid);
8821: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8822: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8823: #&logthis("rndseed :$num:$symb");
1.564 albertel 8824: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8825: return $num;
8826: }
8827: }
8828:
8829: sub rndseed_64bit {
8830: my ($symb,$courseid,$domain,$username)=@_;
8831: {
8832: use integer;
8833: my $symbchck=unpack("%32S*",$symb) << 21;
8834: my $symbseed=numval($symb) << 10;
8835: my $namechck=unpack("%32S*",$username);
8836:
8837: my $nameseed=numval($username) << 21;
8838: my $domainseed=unpack("%32S*",$domain) << 10;
8839: my $courseseed=unpack("%32S*",$courseid);
8840:
8841: my $num1=$symbchck+$symbseed+$namechck;
8842: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8843: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8844: #&logthis("rndseed :$num:$symb");
1.564 albertel 8845: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8846: return "$num1,$num2";
1.155 albertel 8847: }
1.366 albertel 8848: }
8849:
1.443 albertel 8850: sub rndseed_64bit2 {
8851: my ($symb,$courseid,$domain,$username)=@_;
8852: {
8853: use integer;
8854: # strings need to be an even # of cahracters long, it it is odd the
8855: # last characters gets thrown away
8856: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8857: my $symbseed=numval($symb) << 10;
8858: my $namechck=unpack("%32S*",$username.' ');
8859:
8860: my $nameseed=numval($username) << 21;
1.501 albertel 8861: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8862: my $courseseed=unpack("%32S*",$courseid.' ');
8863:
8864: my $num1=$symbchck+$symbseed+$namechck;
8865: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8866: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8867: #&logthis("rndseed :$num:$symb");
1.803 albertel 8868: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8869: return "$num1,$num2";
8870: }
8871: }
8872:
8873: sub rndseed_64bit3 {
8874: my ($symb,$courseid,$domain,$username)=@_;
8875: {
8876: use integer;
8877: # strings need to be an even # of cahracters long, it it is odd the
8878: # last characters gets thrown away
8879: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8880: my $symbseed=numval2($symb) << 10;
8881: my $namechck=unpack("%32S*",$username.' ');
8882:
8883: my $nameseed=numval2($username) << 21;
1.443 albertel 8884: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8885: my $courseseed=unpack("%32S*",$courseid.' ');
8886:
8887: my $num1=$symbchck+$symbseed+$namechck;
8888: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8889: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8890: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8891: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8892:
1.503 albertel 8893: return "$num1:$num2";
1.443 albertel 8894: }
8895: }
8896:
1.575 albertel 8897: sub rndseed_64bit4 {
8898: my ($symb,$courseid,$domain,$username)=@_;
8899: {
8900: use integer;
8901: # strings need to be an even # of cahracters long, it it is odd the
8902: # last characters gets thrown away
8903: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8904: my $symbseed=numval3($symb) << 10;
8905: my $namechck=unpack("%32S*",$username.' ');
8906:
8907: my $nameseed=numval3($username) << 21;
8908: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8909: my $courseseed=unpack("%32S*",$courseid.' ');
8910:
8911: my $num1=$symbchck+$symbseed+$namechck;
8912: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8913: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8914: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8915: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8916:
8917: return "$num1:$num2";
8918: }
8919: }
8920:
1.675 albertel 8921: sub rndseed_64bit5 {
8922: my ($symb,$courseid,$domain,$username)=@_;
8923: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8924: return "$num1:$num2";
8925: }
8926:
1.366 albertel 8927: sub rndseed_CODE_64bit {
8928: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8929: {
1.366 albertel 8930: use integer;
1.443 albertel 8931: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8932: my $symbseed=numval2($symb);
1.491 albertel 8933: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8934: my $CODEseed=numval(&getCODE());
1.443 albertel 8935: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8936: my $num1=$symbseed+$CODEchck;
8937: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8938: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8939: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8940: if ($_64bit) { $num1=(($num1<<32)>>32); }
8941: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8942: return "$num1:$num2";
1.366 albertel 8943: }
8944: }
8945:
1.575 albertel 8946: sub rndseed_CODE_64bit4 {
8947: my ($symb,$courseid,$domain,$username)=@_;
8948: {
8949: use integer;
8950: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8951: my $symbseed=numval3($symb);
8952: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8953: my $CODEseed=numval3(&getCODE());
8954: my $courseseed=unpack("%32S*",$courseid.' ');
8955: my $num1=$symbseed+$CODEchck;
8956: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8957: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8958: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8959: if ($_64bit) { $num1=(($num1<<32)>>32); }
8960: if ($_64bit) { $num2=(($num2<<32)>>32); }
8961: return "$num1:$num2";
8962: }
8963: }
8964:
1.675 albertel 8965: sub rndseed_CODE_64bit5 {
8966: my ($symb,$courseid,$domain,$username)=@_;
8967: my $code = &getCODE();
8968: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8969: return "$num1:$num2";
8970: }
8971:
1.366 albertel 8972: sub setup_random_from_rndseed {
8973: my ($rndseed)=@_;
1.503 albertel 8974: if ($rndseed =~/([,:])/) {
8975: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8976: &Math::Random::random_set_seed(abs($num1),abs($num2));
8977: } else {
8978: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8979: }
1.36 albertel 8980: }
8981:
1.474 albertel 8982: sub latest_receipt_algorithm_id {
1.835 albertel 8983: return 'receipt3';
1.474 albertel 8984: }
8985:
1.480 www 8986: sub recunique {
8987: my $fucourseid=shift;
8988: my $unique;
1.835 albertel 8989: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8990: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8991: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8992: } else {
8993: $unique=$perlvar{'lonReceipt'};
8994: }
8995: return unpack("%32C*",$unique);
8996: }
8997:
8998: sub recprefix {
8999: my $fucourseid=shift;
9000: my $prefix;
1.835 albertel 9001: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9002: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9003: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9004: } else {
9005: $prefix=$perlvar{'lonHostID'};
9006: }
9007: return unpack("%32C*",$prefix);
9008: }
9009:
1.76 www 9010: sub ireceipt {
1.474 albertel 9011: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9012:
9013: my $return =&recprefix($fucourseid).'-';
9014:
9015: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9016: $env{'request.state'} eq 'construct') {
9017: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9018: return $return;
9019: }
9020:
1.76 www 9021: my $cuname=unpack("%32C*",$funame);
9022: my $cudom=unpack("%32C*",$fudom);
9023: my $cucourseid=unpack("%32C*",$fucourseid);
9024: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9025: my $cunique=&recunique($fucourseid);
1.474 albertel 9026: my $cpart=unpack("%32S*",$part);
1.835 albertel 9027: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9028:
1.790 albertel 9029: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9030:
9031: $return.= ($cunique%$cuname+
9032: $cunique%$cudom+
9033: $cusymb%$cuname+
9034: $cusymb%$cudom+
9035: $cucourseid%$cuname+
9036: $cucourseid%$cudom+
9037: $cpart%$cuname+
9038: $cpart%$cudom);
9039: } else {
9040: $return.= ($cunique%$cuname+
9041: $cunique%$cudom+
9042: $cusymb%$cuname+
9043: $cusymb%$cudom+
9044: $cucourseid%$cuname+
9045: $cucourseid%$cudom);
9046: }
9047: return $return;
1.76 www 9048: }
9049:
9050: sub receipt {
1.474 albertel 9051: my ($part)=@_;
1.790 albertel 9052: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9053: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9054: }
1.260 ng 9055:
1.790 albertel 9056: sub whichuser {
9057: my ($passedsymb)=@_;
9058: my ($symb,$courseid,$domain,$name,$publicuser);
9059: if (defined($env{'form.grade_symb'})) {
9060: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9061: my $allowed=&allowed('vgr',$tmp_courseid);
9062: if (!$allowed &&
9063: exists($env{'request.course.sec'}) &&
9064: $env{'request.course.sec'} !~ /^\s*$/) {
9065: $allowed=&allowed('vgr',$tmp_courseid.
9066: '/'.$env{'request.course.sec'});
9067: }
9068: if ($allowed) {
9069: ($symb)=&get_env_multiple('form.grade_symb');
9070: $courseid=$tmp_courseid;
9071: ($domain)=&get_env_multiple('form.grade_domain');
9072: ($name)=&get_env_multiple('form.grade_username');
9073: return ($symb,$courseid,$domain,$name,$publicuser);
9074: }
9075: }
9076: if (!$passedsymb) {
9077: $symb=&symbread();
9078: } else {
9079: $symb=$passedsymb;
9080: }
9081: $courseid=$env{'request.course.id'};
9082: $domain=$env{'user.domain'};
9083: $name=$env{'user.name'};
9084: if ($name eq 'public' && $domain eq 'public') {
9085: if (!defined($env{'form.username'})) {
9086: $env{'form.username'}.=time.rand(10000000);
9087: }
9088: $name.=$env{'form.username'};
9089: }
9090: return ($symb,$courseid,$domain,$name,$publicuser);
9091:
9092: }
9093:
1.36 albertel 9094: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9095: # returns either the contents of the file or
9096: # -1 if the file doesn't exist
1.481 raeburn 9097: #
9098: # if the target is a file that was uploaded via DOCS,
9099: # a check will be made to see if a current copy exists on the local server,
9100: # if it does this will be served, otherwise a copy will be retrieved from
9101: # the home server for the course and stored in /home/httpd/html/userfiles on
9102: # the local server.
1.472 albertel 9103:
1.36 albertel 9104: sub getfile {
1.538 albertel 9105: my ($file) = @_;
1.609 banghart 9106: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9107: &repcopy($file);
9108: return &readfile($file);
9109: }
9110:
9111: sub repcopy_userfile {
9112: my ($file)=@_;
1.609 banghart 9113: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9114: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9115: my ($cdom,$cnum,$filename) =
1.811 albertel 9116: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9117: my $uri="/uploaded/$cdom/$cnum/$filename";
9118: if (-e "$file") {
1.828 www 9119: # we already have a local copy, check it out
1.538 albertel 9120: my @fileinfo = stat($file);
1.828 www 9121: my $rtncode;
9122: my $info;
1.538 albertel 9123: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9124: if ($lwpresp ne 'ok') {
1.828 www 9125: # there is no such file anymore, even though we had a local copy
1.482 albertel 9126: if ($rtncode eq '404') {
1.538 albertel 9127: unlink($file);
1.482 albertel 9128: }
9129: return -1;
9130: }
9131: if ($info < $fileinfo[9]) {
1.828 www 9132: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9133: return 'ok';
1.828 www 9134: } else {
9135: # the file is outdated, get rid of it
9136: unlink($file);
1.482 albertel 9137: }
1.828 www 9138: }
9139: # one way or the other, at this point, we don't have the file
9140: # construct the correct path for the file
9141: my @parts = ($cdom,$cnum);
9142: if ($filename =~ m|^(.+)/[^/]+$|) {
9143: push @parts, split(/\//,$1);
9144: }
9145: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9146: foreach my $part (@parts) {
9147: $path .= '/'.$part;
9148: if (!-e $path) {
9149: mkdir($path,0770);
1.482 albertel 9150: }
9151: }
1.828 www 9152: # now the path exists for sure
9153: # get a user agent
9154: my $ua=new LWP::UserAgent;
9155: my $transferfile=$file.'.in.transfer';
9156: # FIXME: this should flock
9157: if (-e $transferfile) { return 'ok'; }
9158: my $request;
9159: $uri=~s/^\///;
1.980 raeburn 9160: my $homeserver = &homeserver($cnum,$cdom);
9161: my $protocol = $protocol{$homeserver};
9162: $protocol = 'http' if ($protocol ne 'https');
9163: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9164: my $response=$ua->request($request,$transferfile);
9165: # did it work?
9166: if ($response->is_error()) {
9167: unlink($transferfile);
9168: &logthis("Userfile repcopy failed for $uri");
9169: return -1;
9170: }
9171: # worked, rename the transfer file
9172: rename($transferfile,$file);
1.607 raeburn 9173: return 'ok';
1.481 raeburn 9174: }
9175:
1.517 albertel 9176: sub tokenwrapper {
9177: my $uri=shift;
1.980 raeburn 9178: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9179: $uri=~s|^/||;
1.620 albertel 9180: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9181: my $token=$1;
1.552 albertel 9182: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9183: if ($udom && $uname && $file) {
9184: $file=~s|(\?\.*)*$||;
1.949 raeburn 9185: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9186: my $homeserver = &homeserver($uname,$udom);
9187: my $protocol = $protocol{$homeserver};
9188: $protocol = 'http' if ($protocol ne 'https');
9189: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9190: (($uri=~/\?/)?'&':'?').'token='.$token.
9191: '&tokenissued='.$perlvar{'lonHostID'};
9192: } else {
9193: return '/adm/notfound.html';
9194: }
9195: }
9196:
1.828 www 9197: # call with reqtype HEAD: get last modification time
9198: # call with reqtype GET: get the file contents
9199: # Do not call this with reqtype GET for large files! It loads everything into memory
9200: #
1.481 raeburn 9201: sub getuploaded {
9202: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9203: $uri=~s/^\///;
1.980 raeburn 9204: my $homeserver = &homeserver($cnum,$cdom);
9205: my $protocol = $protocol{$homeserver};
9206: $protocol = 'http' if ($protocol ne 'https');
9207: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9208: my $ua=new LWP::UserAgent;
9209: my $request=new HTTP::Request($reqtype,$uri);
9210: my $response=$ua->request($request);
9211: $$rtncode = $response->code;
1.482 albertel 9212: if (! $response->is_success()) {
9213: return 'failed';
9214: }
9215: if ($reqtype eq 'HEAD') {
1.486 www 9216: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9217: } elsif ($reqtype eq 'GET') {
9218: $$info = $response->content;
1.472 albertel 9219: }
1.482 albertel 9220: return 'ok';
1.36 albertel 9221: }
9222:
1.481 raeburn 9223: sub readfile {
9224: my $file = shift;
9225: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9226: my $fh;
9227: open($fh,"<$file");
9228: my $a='';
1.800 albertel 9229: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9230: return $a;
9231: }
9232:
1.36 albertel 9233: sub filelocation {
1.590 banghart 9234: my ($dir,$file) = @_;
9235: my $location;
9236: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9237:
9238: if ($file =~ m-^/adm/-) {
9239: $file=~s-^/adm/wrapper/-/-;
9240: $file=~s-^/adm/coursedocs/showdoc/-/-;
9241: }
1.882 albertel 9242:
1.590 banghart 9243: if ($file=~m:^/~:) { # is a contruction space reference
9244: $location = $file;
9245: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9246: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9247: # is a correct contruction space reference
9248: $location = $file;
1.956 raeburn 9249: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9250: $location = $file;
1.609 banghart 9251: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9252: my ($udom,$uname,$filename)=
1.811 albertel 9253: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9254: my $home=&homeserver($uname,$udom);
9255: my $is_me=0;
9256: my @ids=¤t_machine_ids();
9257: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9258: if ($is_me) {
1.955 raeburn 9259: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9260: } else {
9261: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9262: $udom.'/'.$uname.'/'.$filename;
9263: }
1.882 albertel 9264: } elsif ($file =~ m-^/adm/-) {
9265: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9266: } else {
9267: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9268: $file=~s:^/res/:/:;
9269: if ( !( $file =~ m:^/:) ) {
9270: $location = $dir. '/'.$file;
9271: } else {
9272: $location = '/home/httpd/html/res'.$file;
9273: }
1.59 albertel 9274: }
1.590 banghart 9275: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9276: while ($location=~m{/\.\./}) {
9277: if ($location =~ m{/[^/]+/\.\./}) {
9278: $location=~ s{/[^/]+/\.\./}{/}g;
9279: } else {
9280: $location=~ s{/\.\./}{/}g;
9281: }
9282: } #remove dir/..
1.590 banghart 9283: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9284: return $location;
1.46 www 9285: }
1.36 albertel 9286:
1.46 www 9287: sub hreflocation {
9288: my ($dir,$file)=@_;
1.980 raeburn 9289: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9290: $file=filelocation($dir,$file);
1.700 albertel 9291: } elsif ($file=~m-^/adm/-) {
9292: $file=~s-^/adm/wrapper/-/-;
9293: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9294: }
9295: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9296: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9297: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9298: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9299: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9300: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9301: -/uploaded/$1/$2/-x;
1.46 www 9302: }
1.913 albertel 9303: if ($file=~ m{^/userfiles/}) {
9304: $file =~ s{^/userfiles/}{/uploaded/};
9305: }
1.462 albertel 9306: return $file;
1.465 albertel 9307: }
9308:
9309: sub current_machine_domains {
1.853 albertel 9310: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9311: }
9312:
9313: sub machine_domains {
9314: my ($hostname) = @_;
1.465 albertel 9315: my @domains;
1.838 albertel 9316: my %hostname = &all_hostnames();
1.465 albertel 9317: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9318: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9319: if ($hostname eq $name) {
1.844 albertel 9320: push(@domains,&host_domain($id));
1.465 albertel 9321: }
9322: }
9323: return @domains;
9324: }
9325:
9326: sub current_machine_ids {
1.853 albertel 9327: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9328: }
9329:
9330: sub machine_ids {
9331: my ($hostname) = @_;
9332: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9333: my @ids;
1.888 albertel 9334: my %name_to_host = &all_names();
1.889 albertel 9335: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9336: return @{ $name_to_host{$hostname} };
9337: }
9338: return;
1.31 www 9339: }
9340:
1.824 raeburn 9341: sub additional_machine_domains {
9342: my @domains;
9343: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9344: while( my $line = <$fh>) {
9345: $line =~ s/\s//g;
9346: push(@domains,$line);
9347: }
9348: return @domains;
9349: }
9350:
9351: sub default_login_domain {
9352: my $domain = $perlvar{'lonDefDomain'};
9353: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9354: foreach my $posdom (¤t_machine_domains(),
9355: &additional_machine_domains()) {
9356: if (lc($posdom) eq lc($testdomain)) {
9357: $domain=$posdom;
9358: last;
9359: }
9360: }
9361: return $domain;
9362: }
9363:
1.31 www 9364: # ------------------------------------------------------------- Declutters URLs
9365:
9366: sub declutter {
9367: my $thisfn=shift;
1.569 albertel 9368: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9369: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9370: $thisfn=~s/^\///;
1.697 albertel 9371: $thisfn=~s|^adm/wrapper/||;
9372: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9373: $thisfn=~s/^res\///;
1.1032 raeburn 9374: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9375: $thisfn=~s/\?.+$//;
9376: }
1.268 www 9377: return $thisfn;
9378: }
9379:
9380: # ------------------------------------------------------------- Clutter up URLs
9381:
9382: sub clutter {
9383: my $thisfn='/'.&declutter(shift);
1.887 albertel 9384: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9385: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9386: $thisfn='/res'.$thisfn;
9387: }
1.1031 raeburn 9388: if ($thisfn !~m|^/adm|) {
9389: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9390: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9391: } else {
9392: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9393: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9394: if ($embstyle eq 'ssi'
9395: || ($embstyle eq 'hdn')
9396: || ($embstyle eq 'rat')
9397: || ($embstyle eq 'prv')
9398: || ($embstyle eq 'ign')) {
9399: #do nothing with these
9400: } elsif (($embstyle eq 'img')
1.695 albertel 9401: || ($embstyle eq 'emb')
9402: || ($embstyle eq 'wrp')) {
9403: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9404: } elsif ($embstyle eq 'unk'
9405: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9406: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9407: } else {
1.718 www 9408: # &logthis("Got a blank emb style");
1.695 albertel 9409: }
1.694 albertel 9410: }
9411: }
1.31 www 9412: return $thisfn;
1.12 www 9413: }
9414:
1.787 albertel 9415: sub clutter_with_no_wrapper {
9416: my $uri = &clutter(shift);
9417: if ($uri =~ m-^/adm/-) {
9418: $uri =~ s-^/adm/wrapper/-/-;
9419: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9420: }
9421: return $uri;
9422: }
9423:
1.557 albertel 9424: sub freeze_escape {
9425: my ($value)=@_;
9426: if (ref($value)) {
9427: $value=&nfreeze($value);
9428: return '__FROZEN__'.&escape($value);
9429: }
9430: return &escape($value);
9431: }
9432:
1.11 www 9433:
1.557 albertel 9434: sub thaw_unescape {
9435: my ($value)=@_;
9436: if ($value =~ /^__FROZEN__/) {
9437: substr($value,0,10,undef);
9438: $value=&unescape($value);
9439: return &thaw($value);
9440: }
9441: return &unescape($value);
9442: }
9443:
1.436 albertel 9444: sub correct_line_ends {
9445: my ($result)=@_;
9446: $$result =~s/\r\n/\n/mg;
9447: $$result =~s/\r/\n/mg;
1.415 albertel 9448: }
1.1 albertel 9449: # ================================================================ Main Program
9450:
1.184 www 9451: sub goodbye {
1.204 albertel 9452: &logthis("Starting Shut down");
1.443 albertel 9453: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9454: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9455: #converted
1.599 albertel 9456: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9457: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9458: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9459: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9460: #1.1 only
1.870 albertel 9461: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9462: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9463: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9464: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9465: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9466: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9467: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9468: &flushcourselogs();
9469: &logthis("Shutting down");
9470: }
9471:
1.852 albertel 9472: sub get_dns {
1.869 albertel 9473: my ($url,$func,$ignore_cache) = @_;
9474: if (!$ignore_cache) {
9475: my ($content,$cached)=
9476: &Apache::lonnet::is_cached_new('dns',$url);
9477: if ($cached) {
9478: &$func($content);
9479: return;
9480: }
9481: }
9482:
9483: my %alldns;
1.852 albertel 9484: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9485: foreach my $dns (<$config>) {
9486: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9487: my $line = $1;
9488: my ($host,$protocol) = split(/:/,$line);
9489: if ($protocol ne 'https') {
9490: $protocol = 'http';
9491: }
9492: $alldns{$host} = $protocol;
1.869 albertel 9493: }
9494: while (%alldns) {
9495: my ($dns) = keys(%alldns);
1.852 albertel 9496: my $ua=new LWP::UserAgent;
1.979 raeburn 9497: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9498: my $response=$ua->request($request);
1.979 raeburn 9499: delete($alldns{$dns});
1.852 albertel 9500: next if ($response->is_error());
9501: my @content = split("\n",$response->content);
1.869 albertel 9502: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9503: &$func(\@content);
1.869 albertel 9504: return;
1.852 albertel 9505: }
9506: close($config);
1.871 albertel 9507: my $which = (split('/',$url))[3];
9508: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9509: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9510: my @content = <$config>;
9511: &$func(\@content);
9512: return;
1.852 albertel 9513: }
1.327 albertel 9514: # ------------------------------------------------------------ Read domain file
9515: {
1.852 albertel 9516: my $loaded;
1.846 albertel 9517: my %domain;
9518:
1.852 albertel 9519: sub parse_domain_tab {
9520: my ($lines) = @_;
9521: foreach my $line (@$lines) {
9522: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9523:
1.846 albertel 9524: chomp($line);
1.852 albertel 9525: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9526: my %this_domain;
9527: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9528: 'lang_def', 'city', 'longi', 'lati',
9529: 'primary') {
9530: $this_domain{$field} = shift(@elements);
9531: }
9532: $domain{$name} = \%this_domain;
1.852 albertel 9533: }
9534: }
1.864 albertel 9535:
9536: sub reset_domain_info {
9537: undef($loaded);
9538: undef(%domain);
9539: }
9540:
1.852 albertel 9541: sub load_domain_tab {
1.869 albertel 9542: my ($ignore_cache) = @_;
9543: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9544: my $fh;
9545: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9546: my @lines = <$fh>;
9547: &parse_domain_tab(\@lines);
1.448 albertel 9548: }
1.852 albertel 9549: close($fh);
9550: $loaded = 1;
1.327 albertel 9551: }
1.846 albertel 9552:
9553: sub domain {
1.852 albertel 9554: &load_domain_tab() if (!$loaded);
9555:
1.846 albertel 9556: my ($name,$what) = @_;
9557: return if ( !exists($domain{$name}) );
9558:
9559: if (!$what) {
9560: return $domain{$name}{'description'};
9561: }
9562: return $domain{$name}{$what};
9563: }
1.974 raeburn 9564:
9565: sub domain_info {
9566: &load_domain_tab() if (!$loaded);
9567: return %domain;
9568: }
9569:
1.327 albertel 9570: }
9571:
9572:
1.1 albertel 9573: # ------------------------------------------------------------- Read hosts file
9574: {
1.838 albertel 9575: my %hostname;
1.844 albertel 9576: my %hostdom;
1.845 albertel 9577: my %libserv;
1.852 albertel 9578: my $loaded;
1.888 albertel 9579: my %name_to_host;
1.852 albertel 9580:
9581: sub parse_hosts_tab {
9582: my ($file) = @_;
9583: foreach my $configline (@$file) {
9584: next if ($configline =~ /^(\#|\s*$ )/x);
9585: next if ($configline =~ /^\^/);
9586: chomp($configline);
1.968 raeburn 9587: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9588: $name=~s/\s//g;
9589: if ($id && $domain && $role && $name) {
9590: $hostname{$id}=$name;
1.888 albertel 9591: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9592: $hostdom{$id}=$domain;
9593: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9594: if (defined($protocol)) {
9595: if ($protocol eq 'https') {
9596: $protocol{$id} = $protocol;
9597: } else {
9598: $protocol{$id} = 'http';
9599: }
1.968 raeburn 9600: } else {
1.969 raeburn 9601: $protocol{$id} = 'http';
1.968 raeburn 9602: }
1.852 albertel 9603: }
9604: }
9605: }
1.864 albertel 9606:
9607: sub reset_hosts_info {
1.897 albertel 9608: &purge_remembered();
1.864 albertel 9609: &reset_domain_info();
9610: &reset_hosts_ip_info();
1.892 albertel 9611: undef(%name_to_host);
1.864 albertel 9612: undef(%hostname);
9613: undef(%hostdom);
9614: undef(%libserv);
9615: undef($loaded);
9616: }
1.1 albertel 9617:
1.852 albertel 9618: sub load_hosts_tab {
1.869 albertel 9619: my ($ignore_cache) = @_;
9620: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9621: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9622: my @config = <$config>;
9623: &parse_hosts_tab(\@config);
9624: close($config);
9625: $loaded=1;
1.1 albertel 9626: }
1.852 albertel 9627:
1.838 albertel 9628: sub hostname {
1.852 albertel 9629: &load_hosts_tab() if (!$loaded);
9630:
1.838 albertel 9631: my ($lonid) = @_;
9632: return $hostname{$lonid};
9633: }
1.845 albertel 9634:
1.838 albertel 9635: sub all_hostnames {
1.852 albertel 9636: &load_hosts_tab() if (!$loaded);
9637:
1.838 albertel 9638: return %hostname;
9639: }
1.845 albertel 9640:
1.888 albertel 9641: sub all_names {
9642: &load_hosts_tab() if (!$loaded);
9643:
9644: return %name_to_host;
9645: }
9646:
1.974 raeburn 9647: sub all_host_domain {
9648: &load_hosts_tab() if (!$loaded);
9649: return %hostdom;
9650: }
9651:
1.845 albertel 9652: sub is_library {
1.852 albertel 9653: &load_hosts_tab() if (!$loaded);
9654:
1.845 albertel 9655: return exists($libserv{$_[0]});
9656: }
9657:
9658: sub all_library {
1.852 albertel 9659: &load_hosts_tab() if (!$loaded);
9660:
1.845 albertel 9661: return %libserv;
9662: }
9663:
1.1062 droeschl 9664: sub unique_library {
9665: #2x reverse removes all hostnames that appear more than once
9666: my %unique = reverse &all_library();
9667: return reverse %unique;
9668: }
9669:
1.841 albertel 9670: sub get_servers {
1.852 albertel 9671: &load_hosts_tab() if (!$loaded);
9672:
1.841 albertel 9673: my ($domain,$type) = @_;
9674: my %possible_hosts = ($type eq 'library') ? %libserv
9675: : %hostname;
9676: my %result;
1.842 albertel 9677: if (ref($domain) eq 'ARRAY') {
9678: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9679: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9680: $result{$host} = $hostname;
9681: }
9682: }
9683: } else {
9684: while ( my ($host,$hostname) = each(%possible_hosts)) {
9685: if ($hostdom{$host} eq $domain) {
9686: $result{$host} = $hostname;
9687: }
1.841 albertel 9688: }
9689: }
9690: return %result;
9691: }
1.845 albertel 9692:
1.1062 droeschl 9693: sub get_unique_servers {
9694: my %unique = reverse &get_servers(@_);
9695: return reverse %unique;
9696: }
9697:
1.844 albertel 9698: sub host_domain {
1.852 albertel 9699: &load_hosts_tab() if (!$loaded);
9700:
1.844 albertel 9701: my ($lonid) = @_;
9702: return $hostdom{$lonid};
9703: }
9704:
1.841 albertel 9705: sub all_domains {
1.852 albertel 9706: &load_hosts_tab() if (!$loaded);
9707:
1.841 albertel 9708: my %seen;
9709: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9710: return @uniq;
9711: }
1.1 albertel 9712: }
9713:
1.847 albertel 9714: {
9715: my %iphost;
1.856 albertel 9716: my %name_to_ip;
9717: my %lonid_to_ip;
1.869 albertel 9718:
1.847 albertel 9719: sub get_hosts_from_ip {
9720: my ($ip) = @_;
9721: my %iphosts = &get_iphost();
9722: if (ref($iphosts{$ip})) {
9723: return @{$iphosts{$ip}};
9724: }
9725: return;
1.839 albertel 9726: }
1.864 albertel 9727:
9728: sub reset_hosts_ip_info {
9729: undef(%iphost);
9730: undef(%name_to_ip);
9731: undef(%lonid_to_ip);
9732: }
1.856 albertel 9733:
9734: sub get_host_ip {
9735: my ($lonid) = @_;
9736: if (exists($lonid_to_ip{$lonid})) {
9737: return $lonid_to_ip{$lonid};
9738: }
9739: my $name=&hostname($lonid);
9740: my $ip = gethostbyname($name);
9741: return if (!$ip || length($ip) ne 4);
9742: $ip=inet_ntoa($ip);
9743: $name_to_ip{$name} = $ip;
9744: $lonid_to_ip{$lonid} = $ip;
9745: return $ip;
9746: }
1.847 albertel 9747:
9748: sub get_iphost {
1.869 albertel 9749: my ($ignore_cache) = @_;
1.894 albertel 9750:
1.869 albertel 9751: if (!$ignore_cache) {
9752: if (%iphost) {
9753: return %iphost;
9754: }
9755: my ($ip_info,$cached)=
9756: &Apache::lonnet::is_cached_new('iphost','iphost');
9757: if ($cached) {
9758: %iphost = %{$ip_info->[0]};
9759: %name_to_ip = %{$ip_info->[1]};
9760: %lonid_to_ip = %{$ip_info->[2]};
9761: return %iphost;
9762: }
9763: }
1.894 albertel 9764:
9765: # get yesterday's info for fallback
9766: my %old_name_to_ip;
9767: my ($ip_info,$cached)=
9768: &Apache::lonnet::is_cached_new('iphost','iphost');
9769: if ($cached) {
9770: %old_name_to_ip = %{$ip_info->[1]};
9771: }
9772:
1.888 albertel 9773: my %name_to_host = &all_names();
9774: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9775: my $ip;
9776: if (!exists($name_to_ip{$name})) {
9777: $ip = gethostbyname($name);
9778: if (!$ip || length($ip) ne 4) {
1.894 albertel 9779: if (defined($old_name_to_ip{$name})) {
9780: $ip = $old_name_to_ip{$name};
9781: &logthis("Can't find $name defaulting to old $ip");
9782: } else {
9783: &logthis("Name $name no IP found");
9784: next;
9785: }
9786: } else {
9787: $ip=inet_ntoa($ip);
1.847 albertel 9788: }
9789: $name_to_ip{$name} = $ip;
9790: } else {
9791: $ip = $name_to_ip{$name};
1.653 albertel 9792: }
1.888 albertel 9793: foreach my $id (@{ $name_to_host{$name} }) {
9794: $lonid_to_ip{$id} = $ip;
9795: }
9796: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9797: }
1.869 albertel 9798: &Apache::lonnet::do_cache_new('iphost','iphost',
9799: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9800: 48*60*60);
1.869 albertel 9801:
1.847 albertel 9802: return %iphost;
1.598 albertel 9803: }
9804:
1.992 raeburn 9805: #
9806: # Given a DNS returns the loncapa host name for that DNS
9807: #
9808: sub host_from_dns {
9809: my ($dns) = @_;
9810: my @hosts;
9811: my $ip;
9812:
1.993 raeburn 9813: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9814: $ip = $name_to_ip{$dns};
9815: }
9816: if (!$ip) {
9817: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9818: if (length($ip) == 4) {
9819: $ip = &IO::Socket::inet_ntoa($ip);
9820: }
9821: }
9822: if ($ip) {
9823: @hosts = get_hosts_from_ip($ip);
9824: return $hosts[0];
9825: }
9826: return undef;
1.986 foxr 9827: }
1.992 raeburn 9828:
1.986 foxr 9829: }
9830:
1.862 albertel 9831: BEGIN {
9832:
9833: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9834: unless ($readit) {
9835: {
9836: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9837: %perlvar = (%perlvar,%{$configvars});
9838: }
9839:
9840:
1.1 albertel 9841: # ------------------------------------------------------ Read spare server file
9842: {
1.448 albertel 9843: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9844:
9845: while (my $configline=<$config>) {
9846: chomp($configline);
1.284 matthew 9847: if ($configline) {
1.784 albertel 9848: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9849: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9850: push(@{ $spareid{$type} }, $host);
1.1 albertel 9851: }
9852: }
1.448 albertel 9853: close($config);
1.1 albertel 9854: }
1.11 www 9855: # ------------------------------------------------------------ Read permissions
9856: {
1.448 albertel 9857: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9858:
9859: while (my $configline=<$config>) {
1.448 albertel 9860: chomp($configline);
9861: if ($configline) {
9862: my ($role,$perm)=split(/ /,$configline);
9863: if ($perm ne '') { $pr{$role}=$perm; }
9864: }
1.11 www 9865: }
1.448 albertel 9866: close($config);
1.11 www 9867: }
9868:
9869: # -------------------------------------------- Read plain texts for permissions
9870: {
1.448 albertel 9871: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9872:
9873: while (my $configline=<$config>) {
1.448 albertel 9874: chomp($configline);
9875: if ($configline) {
1.742 raeburn 9876: my ($short,@plain)=split(/:/,$configline);
9877: %{$prp{$short}} = ();
9878: if (@plain > 0) {
9879: $prp{$short}{'std'} = $plain[0];
9880: for (my $i=1; $i<@plain; $i++) {
9881: $prp{$short}{'alt'.$i} = $plain[$i];
9882: }
9883: }
1.448 albertel 9884: }
1.135 www 9885: }
1.448 albertel 9886: close($config);
1.135 www 9887: }
9888:
9889: # ---------------------------------------------------------- Read package table
9890: {
1.448 albertel 9891: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9892:
9893: while (my $configline=<$config>) {
1.483 albertel 9894: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9895: chomp($configline);
9896: my ($short,$plain)=split(/:/,$configline);
9897: my ($pack,$name)=split(/\&/,$short);
9898: if ($plain ne '') {
9899: $packagetab{$pack.'&'.$name.'&name'}=$name;
9900: $packagetab{$short}=$plain;
9901: }
1.11 www 9902: }
1.448 albertel 9903: close($config);
1.329 matthew 9904: }
9905:
9906: # ------------- set up temporary directory
9907: {
9908: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9909:
1.11 www 9910: }
9911:
1.794 albertel 9912: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9913: 'compress_threshold'=> 20_000,
9914: });
1.185 www 9915:
1.281 www 9916: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9917: $dumpcount=0;
1.958 www 9918: $locknum=0;
1.22 www 9919:
1.163 harris41 9920: &logtouch();
1.672 albertel 9921: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9922: $readit=1;
1.564 albertel 9923: {
9924: use integer;
9925: my $test=(2**32)+1;
1.568 albertel 9926: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9927: &logthis(" Detected 64bit platform ($_64bit)");
9928: }
1.195 www 9929: }
1.1 albertel 9930: }
1.179 www 9931:
1.1 albertel 9932: 1;
1.191 harris41 9933: __END__
9934:
1.243 albertel 9935: =pod
9936:
1.191 harris41 9937: =head1 NAME
9938:
1.243 albertel 9939: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9940:
9941: =head1 SYNOPSIS
9942:
1.243 albertel 9943: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9944:
9945: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9946:
1.243 albertel 9947: Common parameters:
9948:
9949: =over 4
9950:
9951: =item *
9952:
9953: $uname : an internal username (if $cname expecting a course Id specifically)
9954:
9955: =item *
9956:
9957: $udom : a domain (if $cdom expecting a course's domain specifically)
9958:
9959: =item *
9960:
9961: $symb : a resource instance identifier
9962:
9963: =item *
9964:
9965: $namespace : the name of a .db file that contains the data needed or
9966: being set.
9967:
9968: =back
9969:
1.394 bowersj2 9970: =head1 OVERVIEW
1.191 harris41 9971:
1.394 bowersj2 9972: lonnet provides subroutines which interact with the
9973: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9974: about classes, users, and resources.
1.243 albertel 9975:
9976: For many of these objects you can also use this to store data about
9977: them or modify them in various ways.
1.191 harris41 9978:
1.394 bowersj2 9979: =head2 Symbs
1.191 harris41 9980:
1.394 bowersj2 9981: To identify a specific instance of a resource, LON-CAPA uses symbols
9982: or "symbs"X<symb>. These identifiers are built from the URL of the
9983: map, the resource number of the resource in the map, and the URL of
9984: the resource itself. The latter is somewhat redundant, but might help
9985: if maps change.
9986:
9987: An example is
9988:
9989: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9990:
9991: The respective map entry is
9992:
9993: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9994: title="Problem 2">
9995: </resource>
9996:
9997: Symbs are used by the random number generator, as well as to store and
9998: restore data specific to a certain instance of for example a problem.
9999:
10000: =head2 Storing And Retrieving Data
10001:
10002: X<store()>X<cstore()>X<restore()>Three of the most important functions
10003: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10004: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10005: is is the non-critical message twin of cstore. These functions are for
10006: handlers to store a perl hash to a user's permanent data space in an
10007: easy manner, and to retrieve it again on another call. It is expected
10008: that a handler would use this once at the beginning to retrieve data,
10009: and then again once at the end to send only the new data back.
10010:
10011: The data is stored in the user's data directory on the user's
10012: homeserver under the ID of the course.
10013:
10014: The hash that is returned by restore will have all of the previous
10015: value for all of the elements of the hash.
10016:
10017: Example:
10018:
10019: #creating a hash
10020: my %hash;
10021: $hash{'foo'}='bar';
10022:
10023: #storing it
10024: &Apache::lonnet::cstore(\%hash);
10025:
10026: #changing a value
10027: $hash{'foo'}='notbar';
10028:
10029: #adding a new value
10030: $hash{'bar'}='foo';
10031: &Apache::lonnet::cstore(\%hash);
10032:
10033: #retrieving the hash
10034: my %history=&Apache::lonnet::restore();
10035:
10036: #print the hash
10037: foreach my $key (sort(keys(%history))) {
10038: print("\%history{$key} = $history{$key}");
10039: }
10040:
10041: Will print out:
1.191 harris41 10042:
1.394 bowersj2 10043: %history{1:foo} = bar
10044: %history{1:keys} = foo:timestamp
10045: %history{1:timestamp} = 990455579
10046: %history{2:bar} = foo
10047: %history{2:foo} = notbar
10048: %history{2:keys} = foo:bar:timestamp
10049: %history{2:timestamp} = 990455580
10050: %history{bar} = foo
10051: %history{foo} = notbar
10052: %history{timestamp} = 990455580
10053: %history{version} = 2
10054:
10055: Note that the special hash entries C<keys>, C<version> and
10056: C<timestamp> were added to the hash. C<version> will be equal to the
10057: total number of versions of the data that have been stored. The
10058: C<timestamp> attribute will be the UNIX time the hash was
10059: stored. C<keys> is available in every historical section to list which
10060: keys were added or changed at a specific historical revision of a
10061: hash.
10062:
10063: B<Warning>: do not store the hash that restore returns directly. This
10064: will cause a mess since it will restore the historical keys as if the
10065: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10066:
1.394 bowersj2 10067: Calling convention:
1.191 harris41 10068:
1.394 bowersj2 10069: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10070: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10071:
1.394 bowersj2 10072: For more detailed information, see lonnet specific documentation.
1.191 harris41 10073:
1.394 bowersj2 10074: =head1 RETURN MESSAGES
1.191 harris41 10075:
1.394 bowersj2 10076: =over 4
1.191 harris41 10077:
1.394 bowersj2 10078: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10079:
1.394 bowersj2 10080: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10081: when the connection is brought back up
1.191 harris41 10082:
1.394 bowersj2 10083: =item * B<con_failed>: unable to contact remote host and unable to save message
10084: for later delivery
1.191 harris41 10085:
1.967 bisitz 10086: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10087:
1.394 bowersj2 10088: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10089: that was requested
1.191 harris41 10090:
1.243 albertel 10091: =back
1.191 harris41 10092:
1.243 albertel 10093: =head1 PUBLIC SUBROUTINES
1.191 harris41 10094:
1.243 albertel 10095: =head2 Session Environment Functions
1.191 harris41 10096:
1.243 albertel 10097: =over 4
1.191 harris41 10098:
1.394 bowersj2 10099: =item *
10100: X<appenv()>
1.949 raeburn 10101: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10102: the user envirnoment file, and will be restored for each access this
1.620 albertel 10103: user makes during this session, also modifies the %env for the current
1.949 raeburn 10104: process. Optional rolesarrayref - if defined contains a reference to an array
10105: of roles which are exempt from the restriction on modifying user.role entries
10106: in the user's environment.db and in %env.
1.191 harris41 10107:
10108: =item *
1.394 bowersj2 10109: X<delenv()>
1.987 raeburn 10110: B<delenv($delthis,$regexp)>: removes all items from the session
10111: environment file that begin with $delthis. If the
10112: optional second arg - $regexp - is true, $delthis is treated as a
10113: regular expression, otherwise \Q$delthis\E is used.
10114: The values are also deleted from the current processes %env.
1.191 harris41 10115:
1.795 albertel 10116: =item * get_env_multiple($name)
10117:
10118: gets $name from the %env hash, it seemlessly handles the cases where multiple
10119: values may be defined and end up as an array ref.
10120:
10121: returns an array of values
10122:
1.243 albertel 10123: =back
10124:
10125: =head2 User Information
1.191 harris41 10126:
1.243 albertel 10127: =over 4
1.191 harris41 10128:
10129: =item *
1.394 bowersj2 10130: X<queryauthenticate()>
10131: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10132: authentication scheme
10133:
10134: =item *
1.394 bowersj2 10135: X<authenticate()>
10136: B<authenticate($uname,$upass,$udom)>: try to
10137: authenticate user from domain's lib servers (first use the current
10138: one). C<$upass> should be the users password.
1.191 harris41 10139:
10140: =item *
1.394 bowersj2 10141: X<homeserver()>
10142: B<homeserver($uname,$udom)>: find the server which has
10143: the user's directory and files (there must be only one), this caches
10144: the answer, and also caches if there is a borken connection.
1.191 harris41 10145:
10146: =item *
1.394 bowersj2 10147: X<idget()>
10148: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10149: (IDs are a unique resource in a domain, there must be only 1 ID per
10150: username, and only 1 username per ID in a specific domain) (returns
10151: hash: id=>name,id=>name)
1.191 harris41 10152:
10153: =item *
1.394 bowersj2 10154: X<idrget()>
10155: B<idrget($udom,@unames)>: find the IDs behind a list of
10156: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10157:
10158: =item *
1.394 bowersj2 10159: X<idput()>
10160: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10161:
10162: =item *
1.394 bowersj2 10163: X<rolesinit()>
10164: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10165:
10166: =item *
1.551 albertel 10167: X<getsection()>
10168: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10169: course $cname, return section name/number or '' for "not in course"
10170: and '-1' for "no section"
10171:
10172: =item *
1.394 bowersj2 10173: X<userenvironment()>
10174: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10175: passed in @what from the requested user's environment, returns a hash
10176:
1.858 raeburn 10177: =item *
10178: X<userlog_query()>
1.859 albertel 10179: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10180: activity.log file. %filters defines filters applied when parsing the
10181: log file. These can be start or end timestamps, or the type of action
10182: - log to look for Login or Logout events, check for Checkin or
10183: Checkout, role for role selection. The response is in the form
10184: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10185: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10186:
1.243 albertel 10187: =back
10188:
10189: =head2 User Roles
10190:
10191: =over 4
10192:
10193: =item *
10194:
1.810 raeburn 10195: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10196: F: full access
10197: U,I,K: authentication modes (cxx only)
10198: '': forbidden
10199: 1: user needs to choose course
10200: 2: browse allowed
1.766 albertel 10201: A: passphrase authentication needed
1.243 albertel 10202:
10203: =item *
10204:
10205: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10206: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10207: and course level
10208:
10209: =item *
10210:
1.988 raeburn 10211: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10212: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10213: $type is Course (default) or Community.
1.988 raeburn 10214: If $forcedefault evaluates to true, text returned will be default
10215: text for $type. Otherwise, if this is a course, the text returned
10216: will be a custom name for the role (if defined in the course's
10217: environment). If no custom name is defined the default is returned.
10218:
1.832 raeburn 10219: =item *
10220:
1.935 raeburn 10221: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10222: All arguments are optional. Returns a hash of a roles, either for
10223: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10224: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10225: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10226: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10227: For each key, value is set to colon-separated start and end times for
10228: the role. If no username and domain are specified, will default to
1.934 raeburn 10229: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10230: of role statuses (active, future or previous), roles
10231: (e.g., cc,in, st etc.) and domains of the roles which can be used
10232: to restrict the list of roles reported. If no array ref is
10233: provided for types, will default to return only active roles.
1.834 albertel 10234:
1.243 albertel 10235: =back
10236:
10237: =head2 User Modification
10238:
10239: =over 4
10240:
10241: =item *
10242:
1.957 raeburn 10243: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10244: user for the level given by URL. Optional start and end dates (leave empty
10245: string or zero for "no date")
1.191 harris41 10246:
10247: =item *
10248:
1.243 albertel 10249: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10250: change a users, password, possible return values are: ok,
10251: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10252: refused
1.191 harris41 10253:
10254: =item *
10255:
1.243 albertel 10256: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10257:
10258: =item *
10259:
1.1058 raeburn 10260: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10261: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10262:
10263: will update user information (firstname,middlename,lastname,generation,
10264: permanentemail), and if forceid is true, student/employee ID also.
10265: A user's institutional affiliation(s) can also be updated.
10266: User information fields will not be overwritten with empty entries
10267: unless the field is included in the $candelete array reference.
10268: This array is included when a single user is modified via "Manage Users",
10269: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10270:
10271: =item *
10272:
1.286 matthew 10273: modifystudent
10274:
1.957 raeburn 10275: modify a student's enrollment and identification information.
1.286 matthew 10276: The course id is resolved based on the current users environment.
10277: This means the envoking user must be a course coordinator or otherwise
10278: associated with a course.
10279:
1.297 matthew 10280: This call is essentially a wrapper for lonnet::modifyuser and
10281: lonnet::modify_student_enrollment
1.286 matthew 10282:
10283: Inputs:
10284:
10285: =over 4
10286:
1.957 raeburn 10287: =item B<$udom> Student's loncapa domain
1.286 matthew 10288:
1.957 raeburn 10289: =item B<$uname> Student's loncapa login name
1.286 matthew 10290:
1.964 bisitz 10291: =item B<$uid> Student/Employee ID
1.286 matthew 10292:
1.957 raeburn 10293: =item B<$umode> Student's authentication mode
1.286 matthew 10294:
1.957 raeburn 10295: =item B<$upass> Student's password
1.286 matthew 10296:
1.957 raeburn 10297: =item B<$first> Student's first name
1.286 matthew 10298:
1.957 raeburn 10299: =item B<$middle> Student's middle name
1.286 matthew 10300:
1.957 raeburn 10301: =item B<$last> Student's last name
1.286 matthew 10302:
1.957 raeburn 10303: =item B<$gene> Student's generation
1.286 matthew 10304:
1.957 raeburn 10305: =item B<$usec> Student's section in course
1.286 matthew 10306:
10307: =item B<$end> Unix time of the roles expiration
10308:
10309: =item B<$start> Unix time of the roles start date
10310:
10311: =item B<$forceid> If defined, allow $uid to be changed
10312:
10313: =item B<$desiredhome> server to use as home server for student
10314:
1.957 raeburn 10315: =item B<$email> Student's permanent e-mail address
10316:
10317: =item B<$type> Type of enrollment (auto or manual)
10318:
1.963 raeburn 10319: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10320:
10321: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10322:
1.963 raeburn 10323: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10324:
1.963 raeburn 10325: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10326:
1.963 raeburn 10327: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10328:
1.286 matthew 10329: =back
1.297 matthew 10330:
10331: =item *
10332:
10333: modify_student_enrollment
10334:
10335: Change a students enrollment status in a class. The environment variable
10336: 'role.request.course' must be defined for this function to proceed.
10337:
10338: Inputs:
10339:
10340: =over 4
10341:
10342: =item $udom, students domain
10343:
10344: =item $uname, students name
10345:
10346: =item $uid, students user id
10347:
10348: =item $first, students first name
10349:
10350: =item $middle
10351:
10352: =item $last
10353:
10354: =item $gene
10355:
10356: =item $usec
10357:
10358: =item $end
10359:
10360: =item $start
10361:
1.957 raeburn 10362: =item $type
10363:
10364: =item $locktype
10365:
10366: =item $cid
10367:
10368: =item $selfenroll
10369:
10370: =item $context
10371:
1.297 matthew 10372: =back
10373:
1.191 harris41 10374:
10375: =item *
10376:
1.243 albertel 10377: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10378: custom role; give a custom role to a user for the level given by URL. Specify
10379: name and domain of role author, and role name
1.191 harris41 10380:
10381: =item *
10382:
1.243 albertel 10383: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10384:
10385: =item *
10386:
1.243 albertel 10387: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10388:
10389: =back
10390:
10391: =head2 Course Infomation
10392:
10393: =over 4
1.191 harris41 10394:
10395: =item *
10396:
1.631 albertel 10397: coursedescription($courseid) : returns a hash of information about the
10398: specified course id, including all environment settings for the
10399: course, the description of the course will be in the hash under the
10400: key 'description'
1.191 harris41 10401:
10402: =item *
10403:
1.624 albertel 10404: resdata($name,$domain,$type,@which) : request for current parameter
10405: setting for a specific $type, where $type is either 'course' or 'user',
10406: @what should be a list of parameters to ask about. This routine caches
10407: answers for 5 minutes.
1.243 albertel 10408:
1.877 foxr 10409: =item *
10410:
10411: get_courseresdata($courseid, $domain) : dump the entire course resource
10412: data base, returning a hash that is keyed by the resource name and has
10413: values that are the resource value. I believe that the timestamps and
10414: versions are also returned.
10415:
10416:
1.243 albertel 10417: =back
10418:
10419: =head2 Course Modification
10420:
10421: =over 4
1.191 harris41 10422:
10423: =item *
10424:
1.243 albertel 10425: writecoursepref($courseid,%prefs) : write preferences (environment
10426: database) for a course
1.191 harris41 10427:
10428: =item *
10429:
1.1011 raeburn 10430: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10431:
10432: =item *
10433:
1.1038 raeburn 10434: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10435:
10436: =back
10437:
10438: =head2 Resource Subroutines
10439:
10440: =over 4
1.191 harris41 10441:
10442: =item *
10443:
1.243 albertel 10444: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10445:
10446: =item *
10447:
1.243 albertel 10448: repcopy($filename) : subscribes to the requested file, and attempts to
10449: replicate from the owning library server, Might return
1.607 raeburn 10450: 'unavailable', 'not_found', 'forbidden', 'ok', or
10451: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10452: resource. Expects the local filesystem pathname
10453: (/home/httpd/html/res/....)
10454:
10455: =back
10456:
10457: =head2 Resource Information
10458:
10459: =over 4
1.191 harris41 10460:
10461: =item *
10462:
1.243 albertel 10463: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10464: a vairety of different possible values, $varname should be a request
10465: string, and the other parameters can be used to specify who and what
10466: one is asking about.
10467:
10468: Possible values for $varname are environment.lastname (or other item
10469: from the envirnment hash), user.name (or someother aspect about the
10470: user), resource.0.maxtries (or some other part and parameter of a
10471: resource)
1.204 albertel 10472:
10473: =item *
10474:
1.243 albertel 10475: directcondval($number) : get current value of a condition; reads from a state
10476: string
1.204 albertel 10477:
10478: =item *
10479:
1.243 albertel 10480: condval($condidx) : value of condition index based on state
1.204 albertel 10481:
10482: =item *
10483:
1.243 albertel 10484: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10485: resource's metadata, $what should be either a specific key, or either
10486: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10487: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10488:
10489: this function automatically caches all requests
1.191 harris41 10490:
10491: =item *
10492:
1.243 albertel 10493: metadata_query($query,$custom,$customshow) : make a metadata query against the
10494: network of library servers; returns file handle of where SQL and regex results
10495: will be stored for query
1.191 harris41 10496:
10497: =item *
10498:
1.243 albertel 10499: symbread($filename) : return symbolic list entry (filename argument optional);
10500: returns the data handle
1.191 harris41 10501:
10502: =item *
10503:
1.243 albertel 10504: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10505: a possible symb for the URL in $thisfn, and if is an encryypted
10506: resource that the user accessed using /enc/ returns a 1 on success, 0
10507: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10508: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10509:
1.191 harris41 10510:
10511: =item *
10512:
1.243 albertel 10513: symbclean($symb) : removes versions numbers from a symb, returns the
10514: cleaned symb
1.191 harris41 10515:
10516: =item *
10517:
1.243 albertel 10518: is_on_map($uri) : checks if the $uri is somewhere on the current
10519: course map, user must be in a course for it to work.
1.191 harris41 10520:
10521: =item *
10522:
1.243 albertel 10523: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10524:
10525: =item *
10526:
1.243 albertel 10527: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10528: a random seed, all arguments are optional, if they aren't sent it uses the
10529: environment to derive them. Note: if symb isn't sent and it can't get one
10530: from &symbread it will use the current time as its return value
1.191 harris41 10531:
10532: =item *
10533:
1.243 albertel 10534: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10535: unfakeable, receipt
1.191 harris41 10536:
10537: =item *
10538:
1.620 albertel 10539: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10540:
10541: =item *
10542:
1.243 albertel 10543: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10544:
10545: =item *
10546:
1.243 albertel 10547: 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 10548:
10549: =item *
10550:
1.243 albertel 10551: 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 10552:
10553: =item *
10554:
1.243 albertel 10555: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10556:
10557: =item *
10558:
1.243 albertel 10559: devalidate($symb) : devalidate temporary spreadsheet calculations,
10560: forcing spreadsheet to reevaluate the resource scores next time.
10561:
10562: =back
10563:
10564: =head2 Storing/Retreiving Data
10565:
10566: =over 4
1.191 harris41 10567:
10568: =item *
10569:
1.243 albertel 10570: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10571: for this url; hashref needs to be given and should be a \%hashname; the
10572: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10573: be derived from the env
1.191 harris41 10574:
10575: =item *
10576:
1.243 albertel 10577: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10578: uses critical subroutine
1.191 harris41 10579:
10580: =item *
10581:
1.243 albertel 10582: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10583: all args are optional
1.191 harris41 10584:
10585: =item *
10586:
1.717 albertel 10587: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10588: dumps the complete (or key matching regexp) namespace into a hash
10589: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10590: normally &store()ed into
10591:
10592: $range should be either an integer '100' (give me the first 100
10593: matching records)
10594: or be two integers sperated by a - with no spaces
10595: '30-50' (give me the 30th through the 50th matching
10596: records)
10597:
10598:
10599: =item *
10600:
10601: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10602: replaces a &store() version of data with a replacement set of data
10603: for a particular resource in a namespace passed in the $storehash hash
10604: reference
10605:
10606: =item *
10607:
1.243 albertel 10608: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10609: works very similar to store/cstore, but all data is stored in a
10610: temporary location and can be reset using tmpreset, $storehash should
10611: be a hash reference, returns nothing on success
1.191 harris41 10612:
10613: =item *
10614:
1.243 albertel 10615: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10616: similar to restore, but all data is stored in a temporary location and
10617: can be reset using tmpreset. Returns a hash of values on success,
10618: error string otherwise.
1.191 harris41 10619:
10620: =item *
10621:
1.243 albertel 10622: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10623: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10624:
10625: =item *
10626:
1.243 albertel 10627: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10628: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10629:
10630: =item *
10631:
1.243 albertel 10632: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10633: namesp ($udom and $uname are optional)
1.191 harris41 10634:
10635: =item *
10636:
1.702 albertel 10637: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10638: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10639: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10640:
1.702 albertel 10641: $range should be either an integer '100' (give me the first 100
10642: matching records)
10643: or be two integers sperated by a - with no spaces
10644: '30-50' (give me the 30th through the 50th matching
10645: records)
1.449 matthew 10646: =item *
10647:
10648: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10649: $store can be a scalar, an array reference, or if the amount to be
10650: incremented is > 1, a hash reference.
10651:
10652: ($udom and $uname are optional)
1.191 harris41 10653:
10654: =item *
10655:
1.243 albertel 10656: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10657: ($udom and $uname are optional)
1.191 harris41 10658:
10659: =item *
10660:
1.243 albertel 10661: cput($namespace,$storehash,$udom,$uname) : critical put
10662: ($udom and $uname are optional)
1.191 harris41 10663:
10664: =item *
10665:
1.748 albertel 10666: newput($namespace,$storehash,$udom,$uname) :
10667:
10668: Attempts to store the items in the $storehash, but only if they don't
10669: currently exist, if this succeeds you can be certain that you have
10670: successfully created a new key value pair in the $namespace db.
10671:
10672:
10673: Args:
10674: $namespace: name of database to store values to
10675: $storehash: hashref to store to the db
10676: $udom: (optional) domain of user containing the db
10677: $uname: (optional) name of user caontaining the db
10678:
10679: Returns:
10680: 'ok' -> succeeded in storing all keys of $storehash
10681: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10682: least <key> already existed in the db (other
10683: requested keys may also already exist)
1.967 bisitz 10684: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10685: 'con_lost' -> unable to contact request server
10686: 'refused' -> action was not allowed by remote machine
10687:
10688:
10689: =item *
10690:
1.243 albertel 10691: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10692: reference filled in from namesp (encrypts the return communication)
10693: ($udom and $uname are optional)
1.191 harris41 10694:
10695: =item *
10696:
1.243 albertel 10697: log($udom,$name,$home,$message) : write to permanent log for user; use
10698: critical subroutine
10699:
1.806 raeburn 10700: =item *
10701:
1.860 raeburn 10702: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10703: array reference filled in from namespace found in domain level on either
10704: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10705:
10706: =item *
10707:
1.860 raeburn 10708: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10709: domain level either on specified domain server ($uhome) or primary domain
10710: server ($udom and $uhome are optional)
1.806 raeburn 10711:
1.943 raeburn 10712: =item *
10713:
10714: get_domain_defaults($target_domain) : returns hash with defaults for
10715: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10716: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10717: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10718: Values are retrieved from cache (if current), or from domain's configuration.db
10719: (if available), or lastly from values in lonTabs/dns_domain,tab,
10720: or lonTabs/domain.tab.
10721:
10722: %domdefaults = &get_auth_defaults($target_domain);
10723:
1.243 albertel 10724: =back
10725:
10726: =head2 Network Status Functions
10727:
10728: =over 4
1.191 harris41 10729:
10730: =item *
10731:
10732: dirlist($uri) : return directory list based on URI
10733:
10734: =item *
10735:
1.243 albertel 10736: spareserver() : find server with least workload from spare.tab
10737:
1.986 foxr 10738:
10739: =item *
10740:
10741: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10742: if there is no corresponding loncapa host.
10743:
1.243 albertel 10744: =back
10745:
1.986 foxr 10746:
1.243 albertel 10747: =head2 Apache Request
10748:
10749: =over 4
1.191 harris41 10750:
10751: =item *
10752:
1.243 albertel 10753: ssi($url,%hash) : server side include, does a complete request cycle on url to
10754: localhost, posts hash
10755:
10756: =back
10757:
10758: =head2 Data to String to Data
10759:
10760: =over 4
1.191 harris41 10761:
10762: =item *
10763:
1.243 albertel 10764: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10765: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10766:
10767: =item *
10768:
1.243 albertel 10769: hashref2str($hashref) : convert a hashref into a string complete with
10770: escaping and '=' and '&' separators, supports elements that are
10771: arrayrefs and hashrefs
1.191 harris41 10772:
10773: =item *
10774:
1.243 albertel 10775: arrayref2str($arrayref) : convert an arrayref into a string complete
10776: with escaping and '&' separators, supports elements that are arrayrefs
10777: and hashrefs
1.191 harris41 10778:
10779: =item *
10780:
1.243 albertel 10781: str2hash($string) : convert string to hash using unescaping and
10782: splitting on '=' and '&', supports elements that are arrayrefs and
10783: hashrefs
1.191 harris41 10784:
10785: =item *
10786:
1.243 albertel 10787: str2array($string) : convert string to hash using unescaping and
10788: splitting on '&', supports elements that are arrayrefs and hashrefs
10789:
10790: =back
10791:
10792: =head2 Logging Routines
10793:
10794: =over 4
10795:
10796: These routines allow one to make log messages in the lonnet.log and
10797: lonnet.perm logfiles.
1.191 harris41 10798:
10799: =item *
10800:
1.243 albertel 10801: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10802:
10803: =item *
10804:
1.243 albertel 10805: logthis() : append message to the normal lonnet.log file, it gets
10806: preiodically rolled over and deleted.
1.191 harris41 10807:
10808: =item *
10809:
1.243 albertel 10810: logperm() : append a permanent message to lonnet.perm.log, this log
10811: file never gets deleted by any automated portion of the system, only
10812: messages of critical importance should go in here.
10813:
10814: =back
10815:
10816: =head2 General File Helper Routines
10817:
10818: =over 4
1.191 harris41 10819:
10820: =item *
10821:
1.481 raeburn 10822: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10823: (a) files in /uploaded
10824: (i) If a local copy of the file exists -
10825: compares modification date of local copy with last-modified date for
10826: definitive version stored on home server for course. If local copy is
10827: stale, requests a new version from the home server and stores it.
10828: If the original has been removed from the home server, then local copy
10829: is unlinked.
10830: (ii) If local copy does not exist -
10831: requests the file from the home server and stores it.
10832:
10833: If $caller is 'uploadrep':
10834: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10835: for request for files originally uploaded via DOCS.
10836: - returns 'ok' if fresh local copy now available, -1 otherwise.
10837:
10838: Otherwise:
10839: This indicates a call from the content generation phase of the request.
10840: - returns the entire contents of the file or -1.
10841:
10842: (b) files in /res
10843: - returns the entire contents of a file or -1;
10844: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10845:
1.712 albertel 10846:
10847: =item *
10848:
10849: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10850: reference
10851:
10852: returns either a stat() list of data about the file or an empty list
10853: if the file doesn't exist or couldn't find out about it (connection
10854: problems or user unknown)
10855:
1.191 harris41 10856: =item *
10857:
1.243 albertel 10858: filelocation($dir,$file) : returns file system location of a file
10859: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10860: directory that relative $file lookups are to looked in ($dir of /a/dir
10861: and a file of ../bob will become /a/bob)
1.191 harris41 10862:
10863: =item *
10864:
10865: hreflocation($dir,$file) : returns file system location or a URL; same as
10866: filelocation except for hrefs
10867:
10868: =item *
10869:
10870: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10871:
1.243 albertel 10872: =back
10873:
1.608 albertel 10874: =head2 Usererfile file routines (/uploaded*)
10875:
10876: =over 4
10877:
10878: =item *
10879:
10880: userfileupload(): main rotine for putting a file in a user or course's
10881: filespace, arguments are,
10882:
1.620 albertel 10883: formname - required - this is the name of the element in $env where the
1.608 albertel 10884: filename, and the contents of the file to create/modifed exist
1.620 albertel 10885: the filename is in $env{'form.'.$formname.'.filename'} and the
10886: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10887: coursedoc - if true, store the file in the course of the active role
10888: of the current user
10889: subdir - required - subdirectory to put the file in under ../userfiles/
10890: if undefined, it will be placed in "unknown"
10891:
10892: (This routine calls clean_filename() to remove any dangerous
10893: characters from the filename, and then calls finuserfileupload() to
10894: complete the transaction)
10895:
10896: returns either the url of the uploaded file (/uploaded/....) if successful
10897: and /adm/notfound.html if unsuccessful
10898:
10899: =item *
10900:
10901: clean_filename(): routine for cleaing a filename up for storage in
10902: userfile space, argument is:
10903:
10904: filename - proposed filename
10905:
10906: returns: the new clean filename
10907:
10908: =item *
10909:
10910: finishuserfileupload(): routine that creaes and sends the file to
10911: userspace, probably shouldn't be called directly
10912:
10913: docuname: username or courseid of destination for the file
10914: docudom: domain of user/course of destination for the file
10915: formname: same as for userfileupload()
10916: fname: filename (inculding subdirectories) for the file
10917:
10918: returns either the url of the uploaded file (/uploaded/....) if successful
10919: and /adm/notfound.html if unsuccessful
10920:
10921: =item *
10922:
10923: renameuserfile(): renames an existing userfile to a new name
10924:
10925: Args:
10926: docuname: username or courseid of destination for the file
10927: docudom: domain of user/course of destination for the file
10928: old: current file name (including any subdirs under userfiles)
10929: new: desired file name (including any subdirs under userfiles)
10930:
10931: =item *
10932:
10933: mkdiruserfile(): creates a directory is a userfiles dir
10934:
10935: Args:
10936: docuname: username or courseid of destination for the file
10937: docudom: domain of user/course of destination for the file
10938: dir: dir to create (including any subdirs under userfiles)
10939:
10940: =item *
10941:
10942: removeuserfile(): removes a file that exists in userfiles
10943:
10944: Args:
10945: docuname: username or courseid of destination for the file
10946: docudom: domain of user/course of destination for the file
10947: fname: filname to delete (including any subdirs under userfiles)
10948:
10949: =item *
10950:
10951: removeuploadedurl(): convience function for removeuserfile()
10952:
10953: Args:
10954: url: a full /uploaded/... url to delete
10955:
1.747 albertel 10956: =item *
10957:
10958: get_portfile_permissions():
10959: Args:
10960: domain: domain of user or course contain the portfolio files
10961: user: name of user or num of course contain the portfolio files
10962: Returns:
10963: hashref of a dump of the proper file_permissions.db
10964:
10965:
10966: =item *
10967:
10968: get_access_controls():
10969:
10970: Args:
10971: current_permissions: the hash ref returned from get_portfile_permissions()
10972: group: (optional) the group you want the files associated with
10973: file: (optional) the file you want access info on
10974:
10975: Returns:
1.749 raeburn 10976: a hash (keys are file names) of hashes containing
10977: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10978: values are XML containing access control settings (see below)
1.747 albertel 10979:
10980: Internal notes:
10981:
1.749 raeburn 10982: access controls are stored in file_permissions.db as key=value pairs.
10983: key -> path to file/file_name\0uniqueID:scope_end_start
10984: where scope -> public,guest,course,group,domains or users.
10985: end -> UNIX time for end of access (0 -> no end date)
10986: start -> UNIX time for start of access
10987:
10988: value -> XML description of access control
10989: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10990: <start></start>
10991: <end></end>
10992:
10993: <password></password> for scope type = guest
10994:
10995: <domain></domain> for scope type = course or group
10996: <number></number>
10997: <roles id="">
10998: <role></role>
10999: <access></access>
11000: <section></section>
11001: <group></group>
11002: </roles>
11003:
11004: <dom></dom> for scope type = domains
11005:
11006: <users> for scope type = users
11007: <user>
11008: <uname></uname>
11009: <udom></udom>
11010: </user>
11011: </users>
11012: </scope>
11013:
11014: Access data is also aggregated for each file in an additional key=value pair:
11015: key -> path to file/file_name\0accesscontrol
11016: value -> reference to hash
11017: hash contains key = value pairs
11018: where key = uniqueID:scope_end_start
11019: value = UNIX time record was last updated
11020:
11021: Used to improve speed of look-ups of access controls for each file.
11022:
11023: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11024:
11025: modify_access_controls():
11026:
11027: Modifies access controls for a portfolio file
11028: Args
11029: 1. file name
11030: 2. reference to hash of required changes,
11031: 3. domain
11032: 4. username
11033: where domain,username are the domain of the portfolio owner
11034: (either a user or a course)
11035:
11036: Returns:
11037: 1. result of additions or updates ('ok' or 'error', with error message).
11038: 2. result of deletions ('ok' or 'error', with error message).
11039: 3. reference to hash of any new or updated access controls.
11040: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11041: key = integer (inbound ID)
11042: value = uniqueID
1.747 albertel 11043:
1.608 albertel 11044: =back
11045:
1.243 albertel 11046: =head2 HTTP Helper Routines
11047:
11048: =over 4
11049:
1.191 harris41 11050: =item *
11051:
11052: escape() : unpack non-word characters into CGI-compatible hex codes
11053:
11054: =item *
11055:
11056: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11057:
1.243 albertel 11058: =back
11059:
11060: =head1 PRIVATE SUBROUTINES
11061:
11062: =head2 Underlying communication routines (Shouldn't call)
11063:
11064: =over 4
11065:
11066: =item *
11067:
11068: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11069:
11070: =item *
11071:
11072: reply() : uses subreply to send a message to remote machine, logs all failures
11073:
11074: =item *
11075:
11076: critical() : passes a critical message to another server; if cannot
11077: get through then place message in connection buffer directory and
11078: returns con_delayed, if incapable of saving message, returns
11079: con_failed
11080:
11081: =item *
11082:
11083: reconlonc() : tries to reconnect lonc client processes.
11084:
11085: =back
11086:
11087: =head2 Resource Access Logging
11088:
11089: =over 4
11090:
11091: =item *
11092:
11093: flushcourselogs() : flush (save) buffer logs and access logs
11094:
11095: =item *
11096:
11097: courselog($what) : save message for course in hash
11098:
11099: =item *
11100:
11101: courseacclog($what) : save message for course using &courselog(). Perform
11102: special processing for specific resource types (problems, exams, quizzes, etc).
11103:
1.191 harris41 11104: =item *
11105:
11106: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11107: as a PerlChildExitHandler
1.243 albertel 11108:
11109: =back
11110:
11111: =head2 Other
11112:
11113: =over 4
11114:
11115: =item *
11116:
11117: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11118:
11119: =back
11120:
11121: =cut
1.877 foxr 11122:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>