Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1123
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1123 ! raeburn 4: # $Id: lonnet.pm,v 1.1122 2011/08/01 15:25:04 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
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.1117 foxr 98:
1.1090 raeburn 99: use File::Copy;
1.676 albertel 100:
1.195 www 101: my $readit;
1.550 foxr 102: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 103:
1.619 albertel 104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
1.449 matthew 109:
1.1 albertel 110: # --------------------------------------------------------------------- Logging
1.729 www 111: {
112: my $logid;
113: sub instructor_log {
1.957 raeburn 114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
1.729 www 119: $logid++;
1.957 raeburn 120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 122: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 126: 'exe_time' => $now,
1.730 www 127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
1.957 raeburn 133: },$cdom,$cnum);
1.729 www 134: }
135: }
1.1 albertel 136:
1.163 harris41 137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
1.1 albertel 147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
1.448 albertel 152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
1.448 albertel 155: close($fh);
156: }
1.1 albertel 157: return 1;
158: }
159:
160: sub logperm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.448 albertel 165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
1.1 albertel 169: return 1;
170: }
171:
1.850 albertel 172: sub create_connection {
1.853 albertel 173: my ($hostname,$lonid) = @_;
1.851 albertel 174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
1.890 albertel 178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
1.983 raeburn 185: sub get_server_timezone {
186: my ($cnum,$cdom) = @_;
187: my $home=&homeserver($cnum,$cdom);
188: if ($home ne 'no_host') {
189: my $cachetime = 24*3600;
190: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
191: if (defined($cached)) {
192: return $timezone;
193: } else {
194: my $timezone = &reply('servertimezone',$home);
195: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
196: }
197: }
198: }
1.850 albertel 199:
1.1106 raeburn 200: sub get_server_distarch {
201: my ($lonhost,$ignore_cache) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: return;
205: }
206: my $cachetime = 12*3600;
207: if (!$ignore_cache) {
208: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
209: if (defined($cached)) {
210: return $distarch;
211: }
212: }
213: my $rep = &reply('serverdistarch',$lonhost);
214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
216: $rep eq '') {
217: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
218: }
219: }
220: return;
221: }
222:
1.993 raeburn 223: sub get_server_loncaparev {
1.1073 raeburn 224: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 225: if (defined($lonhost)) {
226: if (!defined(&hostname($lonhost))) {
227: undef($lonhost);
228: }
229: }
230: if (!defined($lonhost)) {
231: if (defined(&domain($dom,'primary'))) {
232: $lonhost=&domain($dom,'primary');
233: if ($lonhost eq 'no_host') {
234: undef($lonhost);
235: }
236: }
237: }
238: if (defined($lonhost)) {
1.1073 raeburn 239: my $cachetime = 12*3600;
240: if (!$ignore_cache) {
241: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
242: if (defined($cached)) {
243: return $loncaparev;
244: }
245: }
246: my ($answer,$loncaparev);
247: my @ids=¤t_machine_ids();
248: if (grep(/^\Q$lonhost\E$/,@ids)) {
249: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 251: $loncaparev = $1;
252: }
253: } else {
254: $answer = &reply('serverloncaparev',$lonhost);
255: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
256: if ($caller eq 'loncron') {
257: my $ua=new LWP::UserAgent;
1.1082 raeburn 258: $ua->timeout(4);
1.1073 raeburn 259: my $protocol = $protocol{$lonhost};
260: $protocol = 'http' if ($protocol ne 'https');
261: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
262: my $request=new HTTP::Request('GET',$url);
263: my $response=$ua->request($request);
264: unless ($response->is_error()) {
265: my $content = $response->content;
1.1081 raeburn 266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
1.1081 raeburn 273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 274: $loncaparev = $1;
275: }
1.993 raeburn 276: }
1.1073 raeburn 277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 278: }
279: }
280:
1.1074 raeburn 281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
285: if (defined($cached)) {
286: return $serverhomeID;
287: }
288: }
289: my $cachetime = 12*3600;
290: my $serverhomeID;
291: if ($caller eq 'loncron') {
292: my @machine_ids = &machine_ids($hostname);
293: foreach my $id (@machine_ids) {
294: my $response = &reply('serverhomeID',$id);
295: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
296: $serverhomeID = $response;
297: last;
298: }
299: }
300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
305: }
306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
307: }
308:
1.1121 raeburn 309: sub get_remote_globals {
310: my ($lonhost,$whathash,$ignore_cache) = @_;
311: my (%returnhash,%whatneeded);
312: if (ref($whathash) eq 'ARRAY') {
313: foreach my $what (sort(keys(%{$whathash}))) {
314: my $type = $whathash->{$what};
315: my $hashid = $lonhost.'-'.$what;
316: my ($result,$cached);
317: unless ($ignore_cache) {
318: ($result,$cached)=&is_cached_new('lonnetglobal',$hashid);
319: $returnhash{$what} = $result;
320: }
321: if (defined($cached)) {
322: $returnhash{$what} = $result;
323: } else {
324: $whatneeded{$what} = $type;
325: }
326: }
327: if (keys(%whatneeded) > 0) {
328: my $requested = &freeze_escape(\%whatneeded);
329: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1122 raeburn 330: unless (($rep=~/^refused/) || ($rep=~/^rejected/) || ($rep eq 'con_lost')) {
1.1121 raeburn 331: my @pairs=split(/\&/,$rep);
332: if ($rep !~ /^error/) {
333: foreach my $item (@pairs) {
334: my ($key,$value)=split(/=/,$item,2);
335: my $what = &unescape($key);
336: my $hashid = $lonhost.'-'.$what;
337: $returnhash{$what}=&thaw_unescape($value);
338: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
339: }
340: }
341: }
342: }
343: }
344: return %returnhash;
345: }
346:
1.1 albertel 347: # -------------------------------------------------- Non-critical communication
348: sub subreply {
349: my ($cmd,$server)=@_;
1.838 albertel 350: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 351: #
352: # With loncnew process trimming, there's a timing hole between lonc server
353: # process exit and the master server picking up the listen on the AF_UNIX
354: # socket. In that time interval, a lock file will exist:
355:
356: my $lockfile=$peerfile.".lock";
357: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
358: sleep(1);
359: }
360: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 361: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 362: #
1.550 foxr 363: # We'll give the connection a few tries before abandoning it. If
364: # connection is not possible, we'll con_lost back to the client.
365: #
366: my $client;
367: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
368: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
369: Type => SOCK_STREAM,
370: Timeout => 10);
1.869 albertel 371: if ($client) {
1.550 foxr 372: last; # Connected!
1.850 albertel 373: } else {
1.853 albertel 374: &create_connection(&hostname($server),$server);
1.550 foxr 375: }
1.850 albertel 376: sleep(1); # Try again later if failed connection.
1.550 foxr 377: }
378: my $answer;
379: if ($client) {
1.704 albertel 380: print $client "sethost:$server:$cmd\n";
1.550 foxr 381: $answer=<$client>;
382: if (!$answer) { $answer="con_lost"; }
383: chomp($answer);
384: } else {
385: $answer = 'con_lost'; # Failed connection.
386: }
1.1 albertel 387: return $answer;
388: }
389:
390: sub reply {
391: my ($cmd,$server)=@_;
1.838 albertel 392: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 393: my $answer=subreply($cmd,$server);
1.65 www 394: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 395: &logthis("<font color=\"blue\">WARNING:".
1.12 www 396: " $cmd to $server returned $answer</font>");
397: }
1.1 albertel 398: return $answer;
399: }
400:
401: # ----------------------------------------------------------- Send USR1 to lonc
402:
403: sub reconlonc {
1.891 albertel 404: my ($lonid) = @_;
405: my $hostname = &hostname($lonid);
406: if ($lonid) {
407: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
408: if ($hostname && -e $peerfile) {
409: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
410: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
411: Type => SOCK_STREAM,
412: Timeout => 10);
413: if ($client) {
414: print $client ("reset_retries\n");
415: my $answer=<$client>;
416: #reset just this one.
417: }
418: }
419: return;
420: }
421:
1.836 www 422: &logthis("Trying to reconnect lonc");
1.1 albertel 423: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 424: if (open(my $fh,"<$loncfile")) {
1.1 albertel 425: my $loncpid=<$fh>;
426: chomp($loncpid);
427: if (kill 0 => $loncpid) {
428: &logthis("lonc at pid $loncpid responding, sending USR1");
429: kill USR1 => $loncpid;
430: sleep 1;
1.836 www 431: } else {
1.12 www 432: &logthis(
1.672 albertel 433: "<font color=\"blue\">WARNING:".
1.12 www 434: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 435: }
436: } else {
1.836 www 437: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 438: }
439: }
440:
441: # ------------------------------------------------------ Critical communication
1.12 www 442:
1.1 albertel 443: sub critical {
444: my ($cmd,$server)=@_;
1.838 albertel 445: unless (&hostname($server)) {
1.672 albertel 446: &logthis("<font color=\"blue\">WARNING:".
1.89 www 447: " Critical message to unknown server ($server)</font>");
448: return 'no_such_host';
449: }
1.1 albertel 450: my $answer=reply($cmd,$server);
451: if ($answer eq 'con_lost') {
452: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 453: my $answer=reply($cmd,$server);
1.1 albertel 454: if ($answer eq 'con_lost') {
455: my $now=time;
456: my $middlename=$cmd;
1.5 www 457: $middlename=substr($middlename,0,16);
1.1 albertel 458: $middlename=~s/\W//g;
459: my $dfilename=
1.305 www 460: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
461: $dumpcount++;
1.1 albertel 462: {
1.448 albertel 463: my $dfh;
464: if (open($dfh,">$dfilename")) {
465: print $dfh "$cmd\n";
466: close($dfh);
467: }
1.1 albertel 468: }
469: sleep 2;
470: my $wcmd='';
471: {
1.448 albertel 472: my $dfh;
473: if (open($dfh,"<$dfilename")) {
474: $wcmd=<$dfh>;
475: close($dfh);
476: }
1.1 albertel 477: }
478: chomp($wcmd);
1.7 www 479: if ($wcmd eq $cmd) {
1.672 albertel 480: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 481: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 482: &logperm("D:$server:$cmd");
483: return 'con_delayed';
484: } else {
1.672 albertel 485: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 486: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 487: &logperm("F:$server:$cmd");
488: return 'con_failed';
489: }
490: }
491: }
492: return $answer;
1.405 albertel 493: }
494:
1.755 albertel 495: # ------------------------------------------- check if return value is an error
496:
497: sub error {
498: my ($result) = @_;
1.756 albertel 499: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 500: if ($2 == 2) { return undef; }
501: return $1;
502: }
503: return undef;
504: }
505:
1.783 albertel 506: sub convert_and_load_session_env {
507: my ($lonidsdir,$handle)=@_;
508: my @profile;
509: {
1.917 albertel 510: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
511: if (!$opened) {
1.915 albertel 512: return 0;
513: }
1.783 albertel 514: flock($idf,LOCK_SH);
515: @profile=<$idf>;
516: close($idf);
517: }
518: my %temp_env;
519: foreach my $line (@profile) {
1.786 albertel 520: if ($line !~ m/=/) {
521: return 0;
522: }
1.783 albertel 523: chomp($line);
524: my ($envname,$envvalue)=split(/=/,$line,2);
525: $temp_env{&unescape($envname)} = &unescape($envvalue);
526: }
527: unlink("$lonidsdir/$handle.id");
528: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
529: 0640)) {
530: %disk_env = %temp_env;
531: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
532: untie(%disk_env);
533: }
1.786 albertel 534: return 1;
1.783 albertel 535: }
536:
1.374 www 537: # ------------------------------------------- Transfer profile into environment
1.780 albertel 538: my $env_loaded;
539: sub transfer_profile_to_env {
1.788 albertel 540: my ($lonidsdir,$handle,$force_transfer) = @_;
541: if (!$force_transfer && $env_loaded) { return; }
1.374 www 542:
1.720 albertel 543: if (!defined($lonidsdir)) {
544: $lonidsdir = $perlvar{'lonIDsDir'};
545: }
546: if (!defined($handle)) {
547: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
548: }
549:
1.786 albertel 550: my $convert;
551: {
1.917 albertel 552: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
553: if (!$opened) {
1.915 albertel 554: return;
555: }
1.786 albertel 556: flock($idf,LOCK_SH);
557: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
558: &GDBM_READER(),0640)) {
559: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
560: untie(%disk_env);
561: } else {
562: $convert = 1;
563: }
564: }
565: if ($convert) {
566: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
567: &logthis("Failed to load session, or convert session.");
568: }
1.374 www 569: }
1.783 albertel 570:
1.786 albertel 571: my %remove;
1.783 albertel 572: while ( my $envname = each(%env) ) {
1.433 matthew 573: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
574: if ($time < time-300) {
1.783 albertel 575: $remove{$key}++;
1.433 matthew 576: }
577: }
578: }
1.783 albertel 579:
1.619 albertel 580: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 581: $env_loaded=1;
1.783 albertel 582: foreach my $expired_key (keys(%remove)) {
1.433 matthew 583: &delenv($expired_key);
1.374 www 584: }
1.1 albertel 585: }
586:
1.916 albertel 587: # ---------------------------------------------------- Check for valid session
588: sub check_for_valid_session {
589: my ($r) = @_;
590: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
591: my $lonid=$cookies{'lonID'};
592: return undef if (!$lonid);
593:
594: my $handle=&LONCAPA::clean_handle($lonid->value);
595: my $lonidsdir=$r->dir_config('lonIDsDir');
596: return undef if (!-e "$lonidsdir/$handle.id");
597:
1.917 albertel 598: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
599: return undef if (!$opened);
1.916 albertel 600:
601: flock($idf,LOCK_SH);
602: my %disk_env;
603: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
604: &GDBM_READER(),0640)) {
605: return undef;
606: }
607:
608: if (!defined($disk_env{'user.name'})
609: || !defined($disk_env{'user.domain'})) {
610: return undef;
611: }
612: return $handle;
613: }
614:
1.830 albertel 615: sub timed_flock {
616: my ($file,$lock_type) = @_;
617: my $failed=0;
618: eval {
619: local $SIG{__DIE__}='DEFAULT';
620: local $SIG{ALRM}=sub {
621: $failed=1;
622: die("failed lock");
623: };
624: alarm(13);
625: flock($file,$lock_type);
626: alarm(0);
627: };
628: if ($failed) {
629: return undef;
630: } else {
631: return 1;
632: }
633: }
634:
1.5 www 635: # ---------------------------------------------------------- Append Environment
636:
637: sub appenv {
1.949 raeburn 638: my ($newenv,$roles) = @_;
639: if (ref($newenv) eq 'HASH') {
640: foreach my $key (keys(%{$newenv})) {
641: my $refused = 0;
642: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
643: $refused = 1;
644: if (ref($roles) eq 'ARRAY') {
645: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
646: if (grep(/^\Q$role\E$/,@{$roles})) {
647: $refused = 0;
648: }
649: }
650: }
651: if ($refused) {
652: &logthis("<font color=\"blue\">WARNING: ".
653: "Attempt to modify environment ".$key." to ".$newenv->{$key}
654: .'</font>');
655: delete($newenv->{$key});
656: } else {
657: $env{$key}=$newenv->{$key};
658: }
659: }
660: my $opened = open(my $env_file,'+<',$env{'user.environment'});
661: if ($opened
662: && &timed_flock($env_file,LOCK_EX)
663: &&
664: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
665: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
666: while (my ($key,$value) = each(%{$newenv})) {
667: $disk_env{$key} = $value;
668: }
669: untie(%disk_env);
1.35 www 670: }
1.191 harris41 671: }
1.56 www 672: return 'ok';
673: }
674: # ----------------------------------------------------- Delete from Environment
675:
676: sub delenv {
1.1104 raeburn 677: my ($delthis,$regexp,$roles) = @_;
678: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
679: my $refused = 1;
680: if (ref($roles) eq 'ARRAY') {
681: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
682: if (grep(/^\Q$role\E$/,@{$roles})) {
683: $refused = 0;
684: }
685: }
686: if ($refused) {
687: &logthis("<font color=\"blue\">WARNING: ".
688: "Attempt to delete from environment ".$delthis);
689: return 'error';
690: }
1.56 www 691: }
1.917 albertel 692: my $opened = open(my $env_file,'+<',$env{'user.environment'});
693: if ($opened
1.915 albertel 694: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 695: &&
696: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
697: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 698: foreach my $key (keys(%disk_env)) {
1.987 raeburn 699: if ($regexp) {
700: if ($key=~/^$delthis/) {
701: delete($env{$key});
702: delete($disk_env{$key});
703: }
704: } else {
705: if ($key=~/^\Q$delthis\E/) {
706: delete($env{$key});
707: delete($disk_env{$key});
708: }
709: }
1.448 albertel 710: }
1.783 albertel 711: untie(%disk_env);
1.5 www 712: }
713: return 'ok';
1.369 albertel 714: }
715:
1.790 albertel 716: sub get_env_multiple {
717: my ($name) = @_;
718: my @values;
719: if (defined($env{$name})) {
720: # exists is it an array
721: if (ref($env{$name})) {
722: @values=@{ $env{$name} };
723: } else {
724: $values[0]=$env{$name};
725: }
726: }
727: return(@values);
728: }
729:
1.958 www 730: # ------------------------------------------------------------------- Locking
731:
732: sub set_lock {
733: my ($text)=@_;
734: $locknum++;
735: my $id=$$.'-'.$locknum;
736: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
737: 'session.lock.'.$id => $text});
738: return $id;
739: }
740:
741: sub get_locks {
742: my $num=0;
743: my %texts=();
744: foreach my $lock (split(/\,/,$env{'session.locks'})) {
745: if ($lock=~/\w/) {
746: $num++;
747: $texts{$lock}=$env{'session.lock.'.$lock};
748: }
749: }
750: return ($num,%texts);
751: }
752:
753: sub remove_lock {
754: my ($id)=@_;
755: my $newlocks='';
756: foreach my $lock (split(/\,/,$env{'session.locks'})) {
757: if (($lock=~/\w/) && ($lock ne $id)) {
758: $newlocks.=','.$lock;
759: }
760: }
761: &appenv({'session.locks' => $newlocks});
762: &delenv('session.lock.'.$id);
763: }
764:
765: sub remove_all_locks {
766: my $activelocks=$env{'session.locks'};
767: foreach my $lock (split(/\,/,$env{'session.locks'})) {
768: if ($lock=~/\w/) {
769: &remove_lock($lock);
770: }
771: }
772: }
773:
774:
1.369 albertel 775: # ------------------------------------------ Find out current server userload
776: sub userload {
777: my $numusers=0;
778: {
779: opendir(LONIDS,$perlvar{'lonIDsDir'});
780: my $filename;
781: my $curtime=time;
782: while ($filename=readdir(LONIDS)) {
1.925 albertel 783: next if ($filename eq '.' || $filename eq '..');
784: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 785: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 786: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 787: }
788: closedir(LONIDS);
789: }
790: my $userloadpercent=0;
791: my $maxuserload=$perlvar{'lonUserLoadLim'};
792: if ($maxuserload) {
1.371 albertel 793: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 794: }
1.372 albertel 795: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 796: return $userloadpercent;
1.283 www 797: }
798:
1.1 albertel 799: # ------------------------------ Find server with least workload from spare.tab
1.11 www 800:
1.1 albertel 801: sub spareserver {
1.1083 raeburn 802: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 803: my $spare_server;
1.370 albertel 804: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 805: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
806: : $userloadpercent;
1.1083 raeburn 807: my ($uint_dom,$remotesessions);
808: if (($udom ne '') && (&domain($udom) ne '')) {
809: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
810: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
811: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
812: $remotesessions = $udomdefaults{'remotesessions'};
813: }
1.1123 ! raeburn 814: my $spareshash = &this_host_spares($udom);
! 815: if (ref($spareshash) eq 'HASH') {
! 816: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
! 817: foreach my $try_server (@{ $spareshash->{'primary'} }) {
! 818: if ($uint_dom) {
! 819: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
! 820: $try_server));
! 821: }
! 822: ($spare_server, $lowest_load) =
! 823: &compare_server_load($try_server, $spare_server, $lowest_load);
! 824: }
1.1083 raeburn 825: }
1.784 albertel 826:
1.1123 ! raeburn 827: my $found_server = ($spare_server ne '' && $lowest_load < 100);
! 828:
! 829: if (!$found_server) {
! 830: if (ref($spareshash->{'default'}) eq 'ARRAY') {
! 831: foreach my $try_server (@{ $spareshash->{'default'} }) {
! 832: if ($uint_dom) {
! 833: next unless (&spare_can_host($udom,$uint_dom,
! 834: $remotesessions,$try_server));
! 835: }
! 836: ($spare_server, $lowest_load) =
! 837: &compare_server_load($try_server, $spare_server, $lowest_load);
! 838: }
! 839: }
! 840: }
1.784 albertel 841: }
842:
843: if (!$want_server_name) {
1.968 raeburn 844: my $protocol = 'http';
845: if ($protocol{$spare_server} eq 'https') {
846: $protocol = $protocol{$spare_server};
847: }
1.1001 raeburn 848: if (defined($spare_server)) {
849: my $hostname = &hostname($spare_server);
1.1083 raeburn 850: if (defined($hostname)) {
1.1001 raeburn 851: $spare_server = $protocol.'://'.$hostname;
852: }
853: }
1.784 albertel 854: }
855: return $spare_server;
856: }
857:
858: sub compare_server_load {
859: my ($try_server, $spare_server, $lowest_load) = @_;
860:
861: my $loadans = &reply('load', $try_server);
862: my $userloadans = &reply('userload',$try_server);
863:
864: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 865: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 866: }
867:
868: my $load;
869: if ($loadans =~ /\d/) {
870: if ($userloadans =~ /\d/) {
871: #both are numbers, pick the bigger one
872: $load = ($loadans > $userloadans) ? $loadans
873: : $userloadans;
1.411 albertel 874: } else {
1.784 albertel 875: $load = $loadans;
1.411 albertel 876: }
1.784 albertel 877: } else {
878: $load = $userloadans;
879: }
880:
881: if (($load =~ /\d/) && ($load < $lowest_load)) {
882: $spare_server = $try_server;
883: $lowest_load = $load;
1.370 albertel 884: }
1.784 albertel 885: return ($spare_server,$lowest_load);
1.202 matthew 886: }
1.914 albertel 887:
888: # --------------------------- ask offload servers if user already has a session
889: sub find_existing_session {
890: my ($udom,$uname) = @_;
1.1123 ! raeburn 891: my $spareshash = &this_host_spares($udom);
! 892: if (ref($spareshash) eq 'HASH') {
! 893: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
! 894: foreach my $try_server (@{ $spareshash->{'primary'} }) {
! 895: return $try_server if (&has_user_session($try_server, $udom, $uname));
! 896: }
! 897: }
! 898: if (ref($spareshash->{'default'}) eq 'ARRAY') {
! 899: foreach my $try_server (@{ $spareshash->{'default'} }) {
! 900: return $try_server if (&has_user_session($try_server, $udom, $uname));
! 901: }
! 902: }
1.914 albertel 903: }
904: return;
905: }
906:
907: # -------------------------------- ask if server already has a session for user
908: sub has_user_session {
909: my ($lonid,$udom,$uname) = @_;
910: my $result = &reply(join(':','userhassession',
911: map {&escape($_)} ($udom,$uname)),$lonid);
912: return 1 if ($result eq 'ok');
913:
914: return 0;
915: }
916:
1.1076 raeburn 917: # --------- determine least loaded server in a user's domain which allows login
918:
919: sub choose_server {
1.1115 raeburn 920: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 921: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 922: my %servers = &get_servers($udom);
1.1076 raeburn 923: my $lowest_load = 30000;
1.1116 raeburn 924: my ($login_host,$hostname,$portal_path);
1.1076 raeburn 925: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 926: my $loginvia;
927: if ($checkloginvia) {
928: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 929: if ($loginvia) {
930: my ($server,$path) = split(/:/,$loginvia);
931: ($login_host, $lowest_load) =
932: &compare_server_load($server, $login_host, $lowest_load);
933: if ($login_host eq $server) {
934: $portal_path = $path;
935: }
936: } else {
937: ($login_host, $lowest_load) =
938: &compare_server_load($lonhost, $login_host, $lowest_load);
939: if ($login_host eq $lonhost) {
940: $portal_path = '';
941: }
942: }
943: } else {
1.1076 raeburn 944: ($login_host, $lowest_load) =
1.1116 raeburn 945: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 946: }
947: }
948: if ($login_host ne '') {
1.1116 raeburn 949: $hostname = &hostname($login_host);
1.1076 raeburn 950: }
1.1116 raeburn 951: return ($login_host,$hostname,$portal_path);
1.1076 raeburn 952: }
953:
1.202 matthew 954: # --------------------------------------------- Try to change a user's password
955:
956: sub changepass {
1.799 raeburn 957: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 958: $currentpass = &escape($currentpass);
959: $newpass = &escape($newpass);
1.1030 raeburn 960: my $lonhost = $perlvar{'lonHostID'};
961: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 962: $server);
963: if (! $answer) {
964: &logthis("No reply on password change request to $server ".
965: "by $uname in domain $udom.");
966: } elsif ($answer =~ "^ok") {
967: &logthis("$uname in $udom successfully changed their password ".
968: "on $server.");
969: } elsif ($answer =~ "^pwchange_failure") {
970: &logthis("$uname in $udom was unable to change their password ".
971: "on $server. The action was blocked by either lcpasswd ".
972: "or pwchange");
973: } elsif ($answer =~ "^non_authorized") {
974: &logthis("$uname in $udom did not get their password correct when ".
975: "attempting to change it on $server.");
976: } elsif ($answer =~ "^auth_mode_error") {
977: &logthis("$uname in $udom attempted to change their password despite ".
978: "not being locally or internally authenticated on $server.");
979: } elsif ($answer =~ "^unknown_user") {
980: &logthis("$uname in $udom attempted to change their password ".
981: "on $server but were unable to because $server is not ".
982: "their home server.");
983: } elsif ($answer =~ "^refused") {
984: &logthis("$server refused to change $uname in $udom password because ".
985: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 986: } elsif ($answer =~ "invalid_client") {
987: &logthis("$server refused to change $uname in $udom password because ".
988: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 989: }
990: return $answer;
1.1 albertel 991: }
992:
1.169 harris41 993: # ----------------------- Try to determine user's current authentication scheme
994:
995: sub queryauthenticate {
996: my ($uname,$udom)=@_;
1.456 albertel 997: my $uhome=&homeserver($uname,$udom);
998: if (!$uhome) {
999: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1000: return 'no_host';
1001: }
1002: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1003: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1004: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1005: }
1.456 albertel 1006: return $answer;
1.169 harris41 1007: }
1008:
1.1 albertel 1009: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1010:
1.1 albertel 1011: sub authenticate {
1.1073 raeburn 1012: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1013: $upass=&escape($upass);
1014: $uname= &LONCAPA::clean_username($uname);
1.836 www 1015: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1016: my $newhome;
1.836 www 1017: if ((!$uhome) || ($uhome eq 'no_host')) {
1018: # Maybe the machine was offline and only re-appeared again recently?
1019: &reconlonc();
1020: # One more
1.952 raeburn 1021: $uhome=&homeserver($uname,$udom,1);
1022: if (($uhome eq 'no_host') && $checkdefauth) {
1023: if (defined(&domain($udom,'primary'))) {
1024: $newhome=&domain($udom,'primary');
1025: }
1026: if ($newhome ne '') {
1027: $uhome = $newhome;
1028: }
1029: }
1.836 www 1030: if ((!$uhome) || ($uhome eq 'no_host')) {
1031: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1032: return 'no_host';
1033: }
1.1 albertel 1034: }
1.1073 raeburn 1035: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1036: if ($answer eq 'authorized') {
1.952 raeburn 1037: if ($newhome) {
1038: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1039: return 'no_account_on_host';
1040: } else {
1041: &logthis("User $uname at $udom authorized by $uhome");
1042: return $uhome;
1043: }
1.471 albertel 1044: }
1045: if ($answer eq 'non_authorized') {
1046: &logthis("User $uname at $udom rejected by $uhome");
1047: return 'no_host';
1.9 www 1048: }
1.471 albertel 1049: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1050: return 'no_host';
1051: }
1052:
1.1073 raeburn 1053: sub can_host_session {
1.1074 raeburn 1054: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1055: my $canhost = 1;
1.1074 raeburn 1056: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1057: if (ref($remotesessions) eq 'HASH') {
1058: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1059: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1060: $canhost = 0;
1061: } else {
1062: $canhost = 1;
1063: }
1064: }
1065: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1066: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1067: $canhost = 1;
1068: } else {
1069: $canhost = 0;
1070: }
1071: }
1072: if ($canhost) {
1073: if ($remotesessions->{'version'} ne '') {
1074: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1075: if ($reqmajor ne '' && $reqminor ne '') {
1076: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1077: my $major = $1;
1078: my $minor = $2;
1079: if (($major < $reqmajor ) ||
1080: (($major == $reqmajor) && ($minor < $reqminor))) {
1081: $canhost = 0;
1082: }
1083: } else {
1084: $canhost = 0;
1085: }
1086: }
1087: }
1088: }
1089: }
1090: if ($canhost) {
1091: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1092: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1093: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1094: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1095: if (($uint_dom ne '') &&
1096: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1097: $canhost = 0;
1098: } else {
1099: $canhost = 1;
1100: }
1101: }
1102: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1103: if (($uint_dom ne '') &&
1104: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1105: $canhost = 1;
1106: } else {
1107: $canhost = 0;
1108: }
1109: }
1110: }
1111: }
1112: return $canhost;
1113: }
1114:
1.1083 raeburn 1115: sub spare_can_host {
1116: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1117: my $canhost=1;
1118: my @intdoms;
1119: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1120: if (ref($internet_names) eq 'ARRAY') {
1121: @intdoms = @{$internet_names};
1122: }
1123: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1124: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1125: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1126: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1127: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1128: $canhost = &can_host_session($udom,$try_server,$remoterev,
1129: $remotesessions,
1130: $defdomdefaults{'hostedsessions'});
1131: }
1132: return $canhost;
1133: }
1134:
1.1123 ! raeburn 1135: sub this_host_spares {
! 1136: my ($dom) = @_;
! 1137: my $cachetime = 60*60*24;
! 1138: my @hosts = ¤t_machine_ids();
! 1139: foreach my $lonhost (@hosts) {
! 1140: if (&host_domain($lonhost) eq $dom) {
! 1141: my ($result,$cached)=&is_cached_new('spares',$dom);
! 1142: if (defined($cached)) {
! 1143: return $result;
! 1144: } else {
! 1145: my %domconfig =
! 1146: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
! 1147: if (ref($domconfig{'usersessions'}) eq 'HASH') {
! 1148: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
! 1149: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
! 1150: return &do_cache_new('spares',$dom,$domconfig{'usersessions'}{'spares'}{$lonhost},$cachetime);
! 1151: }
! 1152: }
! 1153: }
! 1154: }
! 1155: last;
! 1156: }
! 1157: }
! 1158: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
! 1159: my ($result,$cached)=&is_cached_new('spares',$serverhomedom);
! 1160: if (defined($cached)) {
! 1161: return $result;
! 1162: } else {
! 1163: my %homedomconfig =
! 1164: &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
! 1165: if (ref($homedomconfig{'usersessions'}) eq 'HASH') {
! 1166: if (ref($homedomconfig{'usersessions'}{'spares'}) eq 'HASH') {
! 1167: if (ref($homedomconfig{'usersessions'}{'spares'}{$perlvar{'lonHostID'}}) eq 'HASH') {
! 1168: return &do_cache_new('spares',$serverhomedom,$homedomconfig{'usersessions'}{'spares'}{$perlvar{'lonHostID'}},$cachetime);
! 1169: }
! 1170: }
! 1171: }
! 1172: }
! 1173: return \%spareid;
! 1174: }
! 1175:
1.1 albertel 1176: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1177:
1.599 albertel 1178: my %homecache;
1.1 albertel 1179: sub homeserver {
1.230 stredwic 1180: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1181: my $index="$uname:$udom";
1.426 albertel 1182:
1.599 albertel 1183: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1184:
1185: my %servers = &get_servers($udom,'library');
1186: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1187: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1188: exists($badServerCache{$tryserver}));
1.841 albertel 1189:
1190: my $answer=reply("home:$udom:$uname",$tryserver);
1191: if ($answer eq 'found') {
1192: delete($badServerCache{$tryserver});
1193: return $homecache{$index}=$tryserver;
1194: } elsif ($answer eq 'no_host') {
1195: $badServerCache{$tryserver}=1;
1196: }
1.1 albertel 1197: }
1198: return 'no_host';
1.70 www 1199: }
1200:
1201: # ------------------------------------- Find the usernames behind a list of IDs
1202:
1203: sub idget {
1204: my ($udom,@ids)=@_;
1205: my %returnhash=();
1206:
1.841 albertel 1207: my %servers = &get_servers($udom,'library');
1208: foreach my $tryserver (keys(%servers)) {
1209: my $idlist=join('&',@ids);
1210: $idlist=~tr/A-Z/a-z/;
1211: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1212: my @answer=();
1213: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1214: @answer=split(/\&/,$reply);
1215: } ;
1216: my $i;
1217: for ($i=0;$i<=$#ids;$i++) {
1218: if ($answer[$i]) {
1219: $returnhash{$ids[$i]}=$answer[$i];
1220: }
1221: }
1222: }
1.70 www 1223: return %returnhash;
1224: }
1225:
1226: # ------------------------------------- Find the IDs behind a list of usernames
1227:
1228: sub idrget {
1229: my ($udom,@unames)=@_;
1230: my %returnhash=();
1.800 albertel 1231: foreach my $uname (@unames) {
1232: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1233: }
1.70 www 1234: return %returnhash;
1235: }
1236:
1237: # ------------------------------- Store away a list of names and associated IDs
1238:
1239: sub idput {
1240: my ($udom,%ids)=@_;
1241: my %servers=();
1.800 albertel 1242: foreach my $uname (keys(%ids)) {
1243: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1244: my $uhom=&homeserver($uname,$udom);
1.70 www 1245: if ($uhom ne 'no_host') {
1.800 albertel 1246: my $id=&escape($ids{$uname});
1.70 www 1247: $id=~tr/A-Z/a-z/;
1.800 albertel 1248: my $esc_unam=&escape($uname);
1.70 www 1249: if ($servers{$uhom}) {
1.800 albertel 1250: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1251: } else {
1.800 albertel 1252: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1253: }
1254: }
1.191 harris41 1255: }
1.800 albertel 1256: foreach my $server (keys(%servers)) {
1257: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1258: }
1.344 www 1259: }
1260:
1.1023 raeburn 1261: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1262: sub dump_dom {
1.1023 raeburn 1263: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1264: if (!$udom) {
1265: $udom=$env{'user.domain'};
1266: }
1267: my %returnhash;
1.1023 raeburn 1268: if ($udom) {
1269: my $uname = &get_domainconfiguser($udom);
1270: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1271: }
1272: return %returnhash;
1273: }
1274:
1.1023 raeburn 1275: # ------------------------------------------ get items from domain db files
1.806 raeburn 1276:
1277: sub get_dom {
1.860 raeburn 1278: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1279: my $items='';
1280: foreach my $item (@$storearr) {
1281: $items.=&escape($item).'&';
1282: }
1283: $items=~s/\&$//;
1.860 raeburn 1284: if (!$udom) {
1285: $udom=$env{'user.domain'};
1286: if (defined(&domain($udom,'primary'))) {
1287: $uhome=&domain($udom,'primary');
1288: } else {
1.874 albertel 1289: undef($uhome);
1.860 raeburn 1290: }
1291: } else {
1292: if (!$uhome) {
1293: if (defined(&domain($udom,'primary'))) {
1294: $uhome=&domain($udom,'primary');
1295: }
1296: }
1297: }
1298: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1299: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1300: my %returnhash;
1.875 albertel 1301: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1302: return %returnhash;
1303: }
1.806 raeburn 1304: my @pairs=split(/\&/,$rep);
1305: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1306: return @pairs;
1307: }
1308: my $i=0;
1309: foreach my $item (@$storearr) {
1310: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1311: $i++;
1312: }
1313: return %returnhash;
1314: } else {
1.880 banghart 1315: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1316: }
1317: }
1318:
1319: # -------------------------------------------- put items in domain db files
1320:
1321: sub put_dom {
1.860 raeburn 1322: my ($namespace,$storehash,$udom,$uhome)=@_;
1323: if (!$udom) {
1324: $udom=$env{'user.domain'};
1325: if (defined(&domain($udom,'primary'))) {
1326: $uhome=&domain($udom,'primary');
1327: } else {
1.874 albertel 1328: undef($uhome);
1.860 raeburn 1329: }
1330: } else {
1331: if (!$uhome) {
1332: if (defined(&domain($udom,'primary'))) {
1333: $uhome=&domain($udom,'primary');
1334: }
1335: }
1336: }
1337: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1338: my $items='';
1339: foreach my $item (keys(%$storehash)) {
1340: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1341: }
1342: $items=~s/\&$//;
1343: return &reply("putdom:$udom:$namespace:$items",$uhome);
1344: } else {
1.860 raeburn 1345: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1346: }
1347: }
1348:
1.1023 raeburn 1349: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1350: sub newput_dom {
1.1023 raeburn 1351: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1352: my $result;
1353: if (!$udom) {
1354: $udom=$env{'user.domain'};
1355: }
1.1023 raeburn 1356: if ($udom) {
1357: my $uname = &get_domainconfiguser($udom);
1358: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1359: }
1360: return $result;
1361: }
1362:
1.1023 raeburn 1363: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1364: sub del_dom {
1.1023 raeburn 1365: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1366: if (ref($storearr) eq 'ARRAY') {
1367: if (!$udom) {
1368: $udom=$env{'user.domain'};
1369: }
1.1023 raeburn 1370: if ($udom) {
1371: my $uname = &get_domainconfiguser($udom);
1372: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1373: }
1374: }
1375: }
1376:
1.1023 raeburn 1377: # ----------------------------------construct domainconfig user for a domain
1378: sub get_domainconfiguser {
1379: my ($udom) = @_;
1380: return $udom.'-domainconfig';
1381: }
1382:
1.837 raeburn 1383: sub retrieve_inst_usertypes {
1384: my ($udom) = @_;
1385: my (%returnhash,@order);
1.989 raeburn 1386: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1387: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1388: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1389: %returnhash = %{$domdefs{'inststatustypes'}};
1390: @order = @{$domdefs{'inststatusorder'}};
1391: } else {
1392: if (defined(&domain($udom,'primary'))) {
1393: my $uhome=&domain($udom,'primary');
1394: my $rep=&reply("inst_usertypes:$udom",$uhome);
1395: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1396: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1397: return (\%returnhash,\@order);
1398: }
1399: my ($hashitems,$orderitems) = split(/:/,$rep);
1400: my @pairs=split(/\&/,$hashitems);
1401: foreach my $item (@pairs) {
1402: my ($key,$value)=split(/=/,$item,2);
1403: $key = &unescape($key);
1404: next if ($key =~ /^error: 2 /);
1405: $returnhash{$key}=&thaw_unescape($value);
1406: }
1407: my @esc_order = split(/\&/,$orderitems);
1408: foreach my $item (@esc_order) {
1409: push(@order,&unescape($item));
1410: }
1411: } else {
1412: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1413: }
1414: }
1415: return (\%returnhash,\@order);
1416: }
1417:
1.868 raeburn 1418: sub is_domainimage {
1419: my ($url) = @_;
1420: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1421: if (&domain($1) ne '') {
1422: return '1';
1423: }
1424: }
1425: return;
1426: }
1427:
1.899 raeburn 1428: sub inst_directory_query {
1429: my ($srch) = @_;
1430: my $udom = $srch->{'srchdomain'};
1431: my %results;
1432: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1433: my $outcome;
1.899 raeburn 1434: if ($homeserver ne '') {
1.904 albertel 1435: my $queryid=&reply("querysend:instdirsearch:".
1436: &escape($srch->{'srchby'}).':'.
1437: &escape($srch->{'srchterm'}).':'.
1438: &escape($srch->{'srchtype'}),$homeserver);
1439: my $host=&hostname($homeserver);
1440: if ($queryid !~/^\Q$host\E\_/) {
1441: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1442: return;
1443: }
1444: my $response = &get_query_reply($queryid);
1445: my $maxtries = 5;
1446: my $tries = 1;
1447: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1448: $response = &get_query_reply($queryid);
1449: $tries ++;
1450: }
1451:
1452: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1453: if ($response eq 'unavailable') {
1454: $outcome = $response;
1455: } else {
1456: $outcome = 'ok';
1457: my @matches = split(/\n/,$response);
1458: foreach my $match (@matches) {
1459: my ($key,$value) = split(/=/,$match);
1460: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1461: }
1.899 raeburn 1462: }
1463: }
1464: }
1.909 raeburn 1465: return ($outcome,%results);
1.899 raeburn 1466: }
1467:
1468: sub usersearch {
1469: my ($srch) = @_;
1470: my $dom = $srch->{'srchdomain'};
1471: my %results;
1472: my %libserv = &all_library();
1473: my $query = 'usersearch';
1474: foreach my $tryserver (keys(%libserv)) {
1475: if (&host_domain($tryserver) eq $dom) {
1476: my $host=&hostname($tryserver);
1477: my $queryid=
1.911 raeburn 1478: &reply("querysend:".&escape($query).':'.
1479: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1480: &escape($srch->{'srchtype'}).':'.
1481: &escape($srch->{'srchterm'}),$tryserver);
1482: if ($queryid !~/^\Q$host\E\_/) {
1483: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1484: next;
1.899 raeburn 1485: }
1486: my $reply = &get_query_reply($queryid);
1487: my $maxtries = 1;
1488: my $tries = 1;
1489: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1490: $reply = &get_query_reply($queryid);
1491: $tries ++;
1492: }
1493: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1494: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1495: } else {
1.911 raeburn 1496: my @matches;
1497: if ($reply =~ /\n/) {
1498: @matches = split(/\n/,$reply);
1499: } else {
1500: @matches = split(/\&/,$reply);
1501: }
1.899 raeburn 1502: foreach my $match (@matches) {
1503: my ($uname,$udom,%userhash);
1.911 raeburn 1504: foreach my $entry (split(/:/,$match)) {
1505: my ($key,$value) =
1506: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1507: $userhash{$key} = $value;
1508: if ($key eq 'username') {
1509: $uname = $value;
1510: } elsif ($key eq 'domain') {
1511: $udom = $value;
1.911 raeburn 1512: }
1.899 raeburn 1513: }
1514: $results{$uname.':'.$udom} = \%userhash;
1515: }
1516: }
1517: }
1518: }
1519: return %results;
1520: }
1521:
1.912 raeburn 1522: sub get_instuser {
1523: my ($udom,$uname,$id) = @_;
1524: my $homeserver = &domain($udom,'primary');
1525: my ($outcome,%results);
1526: if ($homeserver ne '') {
1527: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1528: &escape($id).':'.&escape($udom),$homeserver);
1529: my $host=&hostname($homeserver);
1530: if ($queryid !~/^\Q$host\E\_/) {
1531: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1532: return;
1533: }
1534: my $response = &get_query_reply($queryid);
1535: my $maxtries = 5;
1536: my $tries = 1;
1537: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1538: $response = &get_query_reply($queryid);
1539: $tries ++;
1540: }
1541: if (!&error($response) && $response ne 'refused') {
1542: if ($response eq 'unavailable') {
1543: $outcome = $response;
1544: } else {
1545: $outcome = 'ok';
1546: my @matches = split(/\n/,$response);
1547: foreach my $match (@matches) {
1548: my ($key,$value) = split(/=/,$match);
1549: $results{&unescape($key)} = &thaw_unescape($value);
1550: }
1551: }
1552: }
1553: }
1554: my %userinfo;
1555: if (ref($results{$uname}) eq 'HASH') {
1556: %userinfo = %{$results{$uname}};
1557: }
1558: return ($outcome,%userinfo);
1559: }
1560:
1561: sub inst_rulecheck {
1.923 raeburn 1562: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1563: my %returnhash;
1564: if ($udom ne '') {
1565: if (ref($rules) eq 'ARRAY') {
1566: @{$rules} = map {&escape($_);} (@{$rules});
1567: my $rulestr = join(':',@{$rules});
1568: my $homeserver=&domain($udom,'primary');
1569: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1570: my $response;
1571: if ($item eq 'username') {
1572: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1573: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1574: $homeserver));
1.923 raeburn 1575: } elsif ($item eq 'id') {
1576: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1577: ':'.&escape($id).':'.$rulestr,
1578: $homeserver));
1.945 raeburn 1579: } elsif ($item eq 'selfcreate') {
1580: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1581: &escape($udom).':'.&escape($uname).
1582: ':'.$rulestr,$homeserver));
1.923 raeburn 1583: }
1.912 raeburn 1584: if ($response ne 'refused') {
1585: my @pairs=split(/\&/,$response);
1586: foreach my $item (@pairs) {
1587: my ($key,$value)=split(/=/,$item,2);
1588: $key = &unescape($key);
1589: next if ($key =~ /^error: 2 /);
1590: $returnhash{$key}=&thaw_unescape($value);
1591: }
1592: }
1593: }
1594: }
1595: }
1596: return %returnhash;
1597: }
1598:
1599: sub inst_userrules {
1.923 raeburn 1600: my ($udom,$check) = @_;
1.912 raeburn 1601: my (%ruleshash,@ruleorder);
1602: if ($udom ne '') {
1603: my $homeserver=&domain($udom,'primary');
1604: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1605: my $response;
1606: if ($check eq 'id') {
1607: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1608: $homeserver);
1.943 raeburn 1609: } elsif ($check eq 'email') {
1610: $response=&reply('instemailrules:'.&escape($udom),
1611: $homeserver);
1.923 raeburn 1612: } else {
1613: $response=&reply('instuserrules:'.&escape($udom),
1614: $homeserver);
1615: }
1.912 raeburn 1616: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1617: ($response ne 'unknown_cmd') &&
1.912 raeburn 1618: ($response ne 'no_such_host')) {
1619: my ($hashitems,$orderitems) = split(/:/,$response);
1620: my @pairs=split(/\&/,$hashitems);
1621: foreach my $item (@pairs) {
1622: my ($key,$value)=split(/=/,$item,2);
1623: $key = &unescape($key);
1624: next if ($key =~ /^error: 2 /);
1625: $ruleshash{$key}=&thaw_unescape($value);
1626: }
1627: my @esc_order = split(/\&/,$orderitems);
1628: foreach my $item (@esc_order) {
1629: push(@ruleorder,&unescape($item));
1630: }
1631: }
1632: }
1633: }
1634: return (\%ruleshash,\@ruleorder);
1635: }
1636:
1.976 raeburn 1637: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1638:
1639: sub get_domain_defaults {
1640: my ($domain) = @_;
1641: my $cachetime = 60*60*24;
1642: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1643: if (defined($cached)) {
1644: if (ref($result) eq 'HASH') {
1645: return %{$result};
1646: }
1647: }
1648: my %domdefaults;
1649: my %domconfig =
1.989 raeburn 1650: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1651: 'requestcourses','inststatus',
1.1073 raeburn 1652: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1653: if (ref($domconfig{'defaults'}) eq 'HASH') {
1654: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1655: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1656: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1657: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1658: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1659: } else {
1660: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1661: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1662: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1663: }
1.976 raeburn 1664: if (ref($domconfig{'quotas'}) eq 'HASH') {
1665: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1666: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1667: } else {
1668: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1669: }
1670: my @usertools = ('aboutme','blog','portfolio');
1671: foreach my $item (@usertools) {
1672: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1673: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1674: }
1675: }
1676: }
1.985 raeburn 1677: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1678: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1679: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1680: }
1681: }
1.989 raeburn 1682: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1683: foreach my $item ('inststatustypes','inststatusorder') {
1684: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1685: }
1686: }
1.1047 raeburn 1687: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1688: foreach my $item ('canuse_pdfforms') {
1689: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1690: }
1691: }
1.1073 raeburn 1692: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1693: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1694: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1695: }
1696: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1697: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1698: }
1699: }
1.943 raeburn 1700: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1701: $cachetime);
1702: return %domdefaults;
1703: }
1704:
1.344 www 1705: # --------------------------------------------------- Assign a key to a student
1706:
1707: sub assign_access_key {
1.364 www 1708: #
1709: # a valid key looks like uname:udom#comments
1710: # comments are being appended
1711: #
1.498 www 1712: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1713: $kdom=
1.620 albertel 1714: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1715: $knum=
1.620 albertel 1716: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1717: $cdom=
1.620 albertel 1718: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1719: $cnum=
1.620 albertel 1720: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1721: $udom=$env{'user.name'} unless (defined($udom));
1722: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1723: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1724: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1725: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1726: # assigned to this person
1727: # - this should not happen,
1.345 www 1728: # unless something went wrong
1729: # the first time around
1730: # ready to assign
1.364 www 1731: $logentry=$1.'; '.$logentry;
1.496 www 1732: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1733: $kdom,$knum) eq 'ok') {
1.345 www 1734: # key now belongs to user
1.346 www 1735: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1736: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1737: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1738: return 'ok';
1739: } else {
1740: return
1741: 'error: Count not permanently assign key, will need to be re-entered later.';
1742: }
1743: } else {
1744: return 'error: Could not assign key, try again later.';
1745: }
1.364 www 1746: } elsif (!$existing{$ckey}) {
1.345 www 1747: # the key does not exist
1748: return 'error: The key does not exist';
1749: } else {
1750: # the key is somebody else's
1751: return 'error: The key is already in use';
1752: }
1.344 www 1753: }
1754:
1.364 www 1755: # ------------------------------------------ put an additional comment on a key
1756:
1757: sub comment_access_key {
1758: #
1759: # a valid key looks like uname:udom#comments
1760: # comments are being appended
1761: #
1762: my ($ckey,$cdom,$cnum,$logentry)=@_;
1763: $cdom=
1.620 albertel 1764: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1765: $cnum=
1.620 albertel 1766: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1767: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1768: if ($existing{$ckey}) {
1769: $existing{$ckey}.='; '.$logentry;
1770: # ready to assign
1.367 www 1771: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1772: $cdom,$cnum) eq 'ok') {
1773: return 'ok';
1774: } else {
1775: return 'error: Count not store comment.';
1776: }
1777: } else {
1778: # the key does not exist
1779: return 'error: The key does not exist';
1780: }
1781: }
1782:
1.344 www 1783: # ------------------------------------------------------ Generate a set of keys
1784:
1785: sub generate_access_keys {
1.364 www 1786: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1787: $cdom=
1.620 albertel 1788: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1789: $cnum=
1.620 albertel 1790: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1791: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1792: unless (($cdom) && ($cnum)) { return 0; }
1793: if ($number>10000) { return 0; }
1794: sleep(2); # make sure don't get same seed twice
1795: srand(time()^($$+($$<<15))); # from "Programming Perl"
1796: my $total=0;
1797: for (my $i=1;$i<=$number;$i++) {
1798: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1799: sprintf("%lx",int(100000*rand)).'-'.
1800: sprintf("%lx",int(100000*rand));
1801: $newkey=~s/1/g/g; # folks mix up 1 and l
1802: $newkey=~s/0/h/g; # and also 0 and O
1803: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1804: if ($existing{$newkey}) {
1805: $i--;
1806: } else {
1.364 www 1807: if (&put('accesskeys',
1808: { $newkey => '# generated '.localtime().
1.620 albertel 1809: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1810: '; '.$logentry },
1811: $cdom,$cnum) eq 'ok') {
1.344 www 1812: $total++;
1813: }
1814: }
1815: }
1.620 albertel 1816: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1817: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1818: return $total;
1819: }
1820:
1821: # ------------------------------------------------------- Validate an accesskey
1822:
1823: sub validate_access_key {
1824: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1825: $cdom=
1.620 albertel 1826: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1827: $cnum=
1.620 albertel 1828: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1829: $udom=$env{'user.domain'} unless (defined($udom));
1830: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1831: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1832: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1833: }
1834:
1835: # ------------------------------------- Find the section of student in a course
1.652 albertel 1836: sub devalidate_getsection_cache {
1837: my ($udom,$unam,$courseid)=@_;
1838: my $hashid="$udom:$unam:$courseid";
1839: &devalidate_cache_new('getsection',$hashid);
1840: }
1.298 matthew 1841:
1.815 albertel 1842: sub courseid_to_courseurl {
1843: my ($courseid) = @_;
1844: #already url style courseid
1845: return $courseid if ($courseid =~ m{^/});
1846:
1847: if (exists($env{'course.'.$courseid.'.num'})) {
1848: my $cnum = $env{'course.'.$courseid.'.num'};
1849: my $cdom = $env{'course.'.$courseid.'.domain'};
1850: return "/$cdom/$cnum";
1851: }
1852:
1853: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1854: if (exists($courseinfo{'num'})) {
1855: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1856: }
1857:
1858: return undef;
1859: }
1860:
1.298 matthew 1861: sub getsection {
1862: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1863: my $cachetime=1800;
1.551 albertel 1864:
1865: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1866: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1867: if (defined($cached)) { return $result; }
1868:
1.298 matthew 1869: my %Pending;
1870: my %Expired;
1871: #
1872: # Each role can either have not started yet (pending), be active,
1873: # or have expired.
1874: #
1875: # If there is an active role, we are done.
1876: #
1877: # If there is more than one role which has not started yet,
1878: # choose the one which will start sooner
1879: # If there is one role which has not started yet, return it.
1880: #
1881: # If there is more than one expired role, choose the one which ended last.
1882: # If there is a role which has expired, return it.
1883: #
1.815 albertel 1884: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1885: my $extra = &freeze_escape({'skipcheck' => 1});
1886: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1887: foreach my $key (keys(%roleshash)) {
1.479 albertel 1888: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1889: my $section=$1;
1890: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1891: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1892: my $now=time;
1.548 albertel 1893: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1894: $Expired{$end}=$section;
1895: next;
1896: }
1.548 albertel 1897: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1898: $Pending{$start}=$section;
1899: next;
1900: }
1.599 albertel 1901: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1902: }
1903: #
1904: # Presumedly there will be few matching roles from the above
1905: # loop and the sorting time will be negligible.
1906: if (scalar(keys(%Pending))) {
1907: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1908: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1909: }
1910: if (scalar(keys(%Expired))) {
1911: my @sorted = sort {$a <=> $b} keys(%Expired);
1912: my $time = pop(@sorted);
1.599 albertel 1913: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1914: }
1.599 albertel 1915: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1916: }
1.70 www 1917:
1.599 albertel 1918: sub save_cache {
1919: &purge_remembered();
1.722 albertel 1920: #&Apache::loncommon::validate_page();
1.620 albertel 1921: undef(%env);
1.780 albertel 1922: undef($env_loaded);
1.599 albertel 1923: }
1.452 albertel 1924:
1.599 albertel 1925: my $to_remember=-1;
1926: my %remembered;
1927: my %accessed;
1928: my $kicks=0;
1929: my $hits=0;
1.849 albertel 1930: sub make_key {
1931: my ($name,$id) = @_;
1.872 albertel 1932: if (length($id) > 65
1933: && length(&escape($id)) > 200) {
1934: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1935: }
1.849 albertel 1936: return &escape($name.':'.$id);
1937: }
1938:
1.599 albertel 1939: sub devalidate_cache_new {
1940: my ($name,$id,$debug) = @_;
1941: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1942: $id=&make_key($name,$id);
1.599 albertel 1943: $memcache->delete($id);
1944: delete($remembered{$id});
1945: delete($accessed{$id});
1946: }
1947:
1948: sub is_cached_new {
1949: my ($name,$id,$debug) = @_;
1.849 albertel 1950: $id=&make_key($name,$id);
1.599 albertel 1951: if (exists($remembered{$id})) {
1952: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1953: $accessed{$id}=[&gettimeofday()];
1954: $hits++;
1955: return ($remembered{$id},1);
1956: }
1957: my $value = $memcache->get($id);
1958: if (!(defined($value))) {
1959: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1960: return (undef,undef);
1.416 albertel 1961: }
1.599 albertel 1962: if ($value eq '__undef__') {
1963: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1964: $value=undef;
1965: }
1966: &make_room($id,$value,$debug);
1967: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1968: return ($value,1);
1969: }
1970:
1971: sub do_cache_new {
1972: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1973: $id=&make_key($name,$id);
1.599 albertel 1974: my $setvalue=$value;
1975: if (!defined($setvalue)) {
1976: $setvalue='__undef__';
1977: }
1.623 albertel 1978: if (!defined($time) ) {
1979: $time=600;
1980: }
1.599 albertel 1981: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1982: my $result = $memcache->set($id,$setvalue,$time);
1983: if (! $result) {
1.872 albertel 1984: &logthis("caching of id -> $id failed");
1.910 albertel 1985: $memcache->disconnect_all();
1.872 albertel 1986: }
1.600 albertel 1987: # need to make a copy of $value
1.919 albertel 1988: &make_room($id,$value,$debug);
1.599 albertel 1989: return $value;
1990: }
1991:
1992: sub make_room {
1993: my ($id,$value,$debug)=@_;
1.919 albertel 1994:
1995: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1996: : $value;
1.599 albertel 1997: if ($to_remember<0) { return; }
1998: $accessed{$id}=[&gettimeofday()];
1999: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2000: my $to_kick;
2001: my $max_time=0;
2002: foreach my $other (keys(%accessed)) {
2003: if (&tv_interval($accessed{$other}) > $max_time) {
2004: $to_kick=$other;
2005: $max_time=&tv_interval($accessed{$other});
2006: }
2007: }
2008: delete($remembered{$to_kick});
2009: delete($accessed{$to_kick});
2010: $kicks++;
2011: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2012: return;
2013: }
2014:
1.599 albertel 2015: sub purge_remembered {
1.604 albertel 2016: #&logthis("Tossing ".scalar(keys(%remembered)));
2017: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2018: undef(%remembered);
2019: undef(%accessed);
1.428 albertel 2020: }
1.70 www 2021: # ------------------------------------- Read an entry from a user's environment
2022:
2023: sub userenvironment {
2024: my ($udom,$unam,@what)=@_;
1.976 raeburn 2025: my $items;
2026: foreach my $item (@what) {
2027: $items.=&escape($item).'&';
2028: }
2029: $items=~s/\&$//;
1.70 www 2030: my %returnhash=();
1.1009 raeburn 2031: my $uhome = &homeserver($unam,$udom);
2032: unless ($uhome eq 'no_host') {
2033: my @answer=split(/\&/,
2034: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2035: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2036: return %returnhash;
2037: }
1.1009 raeburn 2038: my $i;
2039: for ($i=0;$i<=$#what;$i++) {
2040: $returnhash{$what[$i]}=&unescape($answer[$i]);
2041: }
1.70 www 2042: }
2043: return %returnhash;
1.1 albertel 2044: }
2045:
1.617 albertel 2046: # ---------------------------------------------------------- Get a studentphoto
2047: sub studentphoto {
2048: my ($udom,$unam,$ext) = @_;
2049: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2050: if (defined($env{'request.course.id'})) {
1.708 raeburn 2051: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2052: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2053: return(&retrievestudentphoto($udom,$unam,$ext));
2054: } else {
2055: my ($result,$perm_reqd)=
1.707 albertel 2056: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2057: if ($result eq 'ok') {
2058: if (!($perm_reqd eq 'yes')) {
2059: return(&retrievestudentphoto($udom,$unam,$ext));
2060: }
2061: }
2062: }
2063: }
2064: } else {
2065: my ($result,$perm_reqd) =
1.707 albertel 2066: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2067: if ($result eq 'ok') {
2068: if (!($perm_reqd eq 'yes')) {
2069: return(&retrievestudentphoto($udom,$unam,$ext));
2070: }
2071: }
2072: }
2073: return '/adm/lonKaputt/lonlogo_broken.gif';
2074: }
2075:
2076: sub retrievestudentphoto {
2077: my ($udom,$unam,$ext,$type) = @_;
2078: my $home=&Apache::lonnet::homeserver($unam,$udom);
2079: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2080: if ($ret eq 'ok') {
2081: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2082: if ($type eq 'thumbnail') {
2083: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2084: }
2085: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2086: return $tokenurl;
2087: } else {
2088: if ($type eq 'thumbnail') {
2089: return '/adm/lonKaputt/genericstudent_tn.gif';
2090: } else {
2091: return '/adm/lonKaputt/lonlogo_broken.gif';
2092: }
1.617 albertel 2093: }
2094: }
2095:
1.263 www 2096: # -------------------------------------------------------------------- New chat
2097:
2098: sub chatsend {
1.724 raeburn 2099: my ($newentry,$anon,$group)=@_;
1.620 albertel 2100: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2101: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2102: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2103: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2104: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2105: &escape($newentry)).':'.$group,$chome);
1.292 www 2106: }
2107:
2108: # ------------------------------------------ Find current version of a resource
2109:
2110: sub getversion {
2111: my $fname=&clutter(shift);
2112: unless ($fname=~/^\/res\//) { return -1; }
2113: return ¤tversion(&filelocation('',$fname));
2114: }
2115:
2116: sub currentversion {
2117: my $fname=shift;
2118: my $author=$fname;
2119: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2120: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2121: my $home=&homeserver($uname,$udom);
1.292 www 2122: if ($home eq 'no_host') {
2123: return -1;
2124: }
1.1112 www 2125: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2126: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2127: return -1;
2128: }
1.1112 www 2129: return $answer;
1.263 www 2130: }
2131:
1.1111 www 2132: #
2133: # Return special version number of resource if set by override, empty otherwise
2134: #
2135: sub usedversion {
2136: my $fname=shift;
2137: unless ($fname) { $fname=$env{'request.uri'}; }
2138: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2139: if ($urlversion) { return $urlversion; }
2140: return '';
2141: }
2142:
1.1 albertel 2143: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2144:
1.1 albertel 2145: sub subscribe {
2146: my $fname=shift;
1.761 raeburn 2147: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2148: $fname=~s/[\n\r]//g;
1.1 albertel 2149: my $author=$fname;
2150: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2151: my ($udom,$uname)=split(/\//,$author);
2152: my $home=homeserver($uname,$udom);
1.335 albertel 2153: if ($home eq 'no_host') {
2154: return 'not_found';
1.1 albertel 2155: }
2156: my $answer=reply("sub:$fname",$home);
1.64 www 2157: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2158: $answer.=' by '.$home;
2159: }
1.1 albertel 2160: return $answer;
2161: }
2162:
1.8 www 2163: # -------------------------------------------------------------- Replicate file
2164:
2165: sub repcopy {
2166: my $filename=shift;
1.23 www 2167: $filename=~s/\/+/\//g;
1.607 raeburn 2168: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2169: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2170: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2171: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2172: return &repcopy_userfile($filename);
2173: }
1.532 albertel 2174: $filename=~s/[\n\r]//g;
1.8 www 2175: my $transname="$filename.in.transfer";
1.828 www 2176: # FIXME: this should flock
1.607 raeburn 2177: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2178: my $remoteurl=subscribe($filename);
1.64 www 2179: if ($remoteurl =~ /^con_lost by/) {
2180: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2181: return 'unavailable';
1.8 www 2182: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2183: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2184: return 'not_found';
1.64 www 2185: } elsif ($remoteurl =~ /^rejected by/) {
2186: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2187: return 'forbidden';
1.20 www 2188: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2189: return 'ok';
1.8 www 2190: } else {
1.290 www 2191: my $author=$filename;
2192: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2193: my ($udom,$uname)=split(/\//,$author);
2194: my $home=homeserver($uname,$udom);
2195: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2196: my @parts=split(/\//,$filename);
2197: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2198: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2199: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2200: return 'bad_request';
1.8 www 2201: }
2202: my $count;
2203: for ($count=5;$count<$#parts;$count++) {
2204: $path.="/$parts[$count]";
2205: if ((-e $path)!=1) {
2206: mkdir($path,0777);
2207: }
2208: }
2209: my $ua=new LWP::UserAgent;
2210: my $request=new HTTP::Request('GET',"$remoteurl");
2211: my $response=$ua->request($request,$transname);
2212: if ($response->is_error()) {
2213: unlink($transname);
2214: my $message=$response->status_line;
1.672 albertel 2215: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2216: ." LWP get: $message: $filename</font>");
1.607 raeburn 2217: return 'unavailable';
1.8 www 2218: } else {
1.16 www 2219: if ($remoteurl!~/\.meta$/) {
2220: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2221: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2222: if ($mresponse->is_error()) {
2223: unlink($filename.'.meta');
2224: &logthis(
1.672 albertel 2225: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2226: }
2227: }
1.8 www 2228: rename($transname,$filename);
1.607 raeburn 2229: return 'ok';
1.8 www 2230: }
1.290 www 2231: }
1.8 www 2232: }
1.330 www 2233: }
2234:
2235: # ------------------------------------------------ Get server side include body
2236: sub ssi_body {
1.381 albertel 2237: my ($filelink,%form)=@_;
1.606 matthew 2238: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2239: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2240: }
1.953 www 2241: my $output='';
2242: my $response;
1.980 raeburn 2243: if ($filelink=~/^https?\:/) {
1.954 raeburn 2244: ($output,$response)=&externalssi($filelink);
1.953 www 2245: } else {
1.1004 droeschl 2246: $filelink .= $filelink=~/\?/ ? '&' : '?';
2247: $filelink .= 'inhibitmenu=yes';
1.953 www 2248: ($output,$response)=&ssi($filelink,%form);
2249: }
1.778 albertel 2250: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2251: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2252: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2253: if (wantarray) {
2254: return ($output, $response);
2255: } else {
2256: return $output;
2257: }
1.8 www 2258: }
2259:
1.15 www 2260: # --------------------------------------------------------- Server Side Include
2261:
1.782 albertel 2262: sub absolute_url {
2263: my ($host_name) = @_;
2264: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2265: if ($host_name eq '') {
2266: $host_name = $ENV{'SERVER_NAME'};
2267: }
2268: return $protocol.$host_name;
2269: }
2270:
1.942 foxr 2271: #
2272: # Server side include.
2273: # Parameters:
2274: # fn Possibly encrypted resource name/id.
2275: # form Hash that describes how the rendering should be done
2276: # and other things.
1.944 foxr 2277: # Returns:
1.950 raeburn 2278: # Scalar context: The content of the response.
2279: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2280: #
1.15 www 2281: sub ssi {
2282:
1.944 foxr 2283: my ($fn,%form)=@_;
1.15 www 2284: my $ua=new LWP::UserAgent;
1.23 www 2285: my $request;
1.711 albertel 2286:
2287: $form{'no_update_last_known'}=1;
1.895 albertel 2288: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2289: if (%form) {
1.782 albertel 2290: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2291: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2292: } else {
1.782 albertel 2293: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2294: }
2295:
1.15 www 2296: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2297: my $response=$ua->request($request);
2298:
1.944 foxr 2299: if (wantarray) {
2300: return ($response->content, $response);
2301: } else {
2302: return $response->content;
1.942 foxr 2303: }
1.324 www 2304: }
2305:
2306: sub externalssi {
2307: my ($url)=@_;
2308: my $ua=new LWP::UserAgent;
2309: my $request=new HTTP::Request('GET',$url);
2310: my $response=$ua->request($request);
1.954 raeburn 2311: if (wantarray) {
2312: return ($response->content, $response);
2313: } else {
2314: return $response->content;
2315: }
1.15 www 2316: }
1.254 www 2317:
1.492 albertel 2318: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2319:
2320: sub allowuploaded {
2321: my ($srcurl,$url)=@_;
2322: $url=&clutter(&declutter($url));
2323: my $dir=$url;
2324: $dir=~s/\/[^\/]+$//;
2325: my %httpref=();
2326: my $httpurl=&hreflocation('',$url);
2327: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2328: &Apache::lonnet::appenv(\%httpref);
1.254 www 2329: }
1.477 raeburn 2330:
1.478 albertel 2331: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2332: # input: action, courseID, current domain, intended
1.637 raeburn 2333: # path to file, source of file, instruction to parse file for objects,
2334: # ref to hash for embedded objects,
2335: # ref to hash for codebase of java objects.
1.1095 raeburn 2336: # reference to scalar to accommodate mime type determined
2337: # from File::MMagic if $parser = parse.
1.637 raeburn 2338: #
1.485 raeburn 2339: # output: url to file (if action was uploaddoc),
2340: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2341: #
1.478 albertel 2342: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2343: # course.
1.477 raeburn 2344: #
1.478 albertel 2345: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2346: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2347: # course's home server.
1.477 raeburn 2348: #
1.478 albertel 2349: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2350: # be copied from $source (current location) to
2351: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2352: # and will then be copied to
2353: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2354: # course's home server.
1.485 raeburn 2355: #
1.481 raeburn 2356: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2357: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2358: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2359: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2360: # in course's home server.
1.637 raeburn 2361: #
1.477 raeburn 2362:
2363: sub process_coursefile {
1.1095 raeburn 2364: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2365: $mimetype)=@_;
1.477 raeburn 2366: my $fetchresult;
1.638 albertel 2367: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2368: if ($action eq 'propagate') {
1.638 albertel 2369: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2370: $home);
1.481 raeburn 2371: } else {
1.477 raeburn 2372: my $fpath = '';
2373: my $fname = $file;
1.478 albertel 2374: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2375: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2376: my $filepath = &build_filepath($fpath);
1.481 raeburn 2377: if ($action eq 'copy') {
2378: if ($source eq '') {
2379: $fetchresult = 'no source file';
2380: return $fetchresult;
2381: } else {
2382: my $destination = $filepath.'/'.$fname;
2383: rename($source,$destination);
2384: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2385: $home);
1.481 raeburn 2386: }
2387: } elsif ($action eq 'uploaddoc') {
2388: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2389: print $fh $env{'form.'.$source};
1.481 raeburn 2390: close($fh);
1.637 raeburn 2391: if ($parser eq 'parse') {
1.1024 raeburn 2392: my $mm = new File::MMagic;
1.1095 raeburn 2393: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2394: if ($type eq 'text/html') {
1.1024 raeburn 2395: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2396: unless ($parse_result eq 'ok') {
2397: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2398: }
1.637 raeburn 2399: }
1.1095 raeburn 2400: if (ref($mimetype)) {
2401: $$mimetype = $type;
2402: }
1.637 raeburn 2403: }
1.477 raeburn 2404: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2405: $home);
1.481 raeburn 2406: if ($fetchresult eq 'ok') {
2407: return '/uploaded/'.$fpath.'/'.$fname;
2408: } else {
2409: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2410: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2411: return '/adm/notfound.html';
2412: }
1.477 raeburn 2413: }
2414: }
1.485 raeburn 2415: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2416: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2417: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2418: }
2419: return $fetchresult;
2420: }
2421:
1.637 raeburn 2422: sub build_filepath {
2423: my ($fpath) = @_;
2424: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2425: unless ($fpath eq '') {
2426: my @parts=split('/',$fpath);
2427: foreach my $part (@parts) {
2428: $filepath.= '/'.$part;
2429: if ((-e $filepath)!=1) {
2430: mkdir($filepath,0777);
2431: }
2432: }
2433: }
2434: return $filepath;
2435: }
2436:
2437: sub store_edited_file {
1.638 albertel 2438: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2439: my $file = $primary_url;
2440: $file =~ s#^/uploaded/$docudom/$docuname/##;
2441: my $fpath = '';
2442: my $fname = $file;
2443: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2444: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2445: my $filepath = &build_filepath($fpath);
2446: open(my $fh,'>'.$filepath.'/'.$fname);
2447: print $fh $content;
2448: close($fh);
1.638 albertel 2449: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2450: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2451: $home);
1.637 raeburn 2452: if ($$fetchresult eq 'ok') {
2453: return '/uploaded/'.$fpath.'/'.$fname;
2454: } else {
1.638 albertel 2455: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2456: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2457: return '/adm/notfound.html';
2458: }
2459: }
2460:
1.531 albertel 2461: sub clean_filename {
1.831 albertel 2462: my ($fname,$args)=@_;
1.315 www 2463: # Replace Windows backslashes by forward slashes
1.257 www 2464: $fname=~s/\\/\//g;
1.831 albertel 2465: if (!$args->{'keep_path'}) {
2466: # Get rid of everything but the actual filename
2467: $fname=~s/^.*\/([^\/]+)$/$1/;
2468: }
1.315 www 2469: # Replace spaces by underscores
2470: $fname=~s/\s+/\_/g;
2471: # Replace all other weird characters by nothing
1.831 albertel 2472: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2473: # Replace all .\d. sequences with _\d. so they no longer look like version
2474: # numbers
2475: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2476: return $fname;
2477: }
1.1051 raeburn 2478: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2479: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2480: # image with the same aspect ratio as the original, but with dimensions which do
2481: # not exceed $resizewidth and $resizeheight.
2482:
1.984 neumanie 2483: sub resizeImage {
1.1051 raeburn 2484: my ($img_path,$resizewidth,$resizeheight) = @_;
2485: my $ima = Image::Magick->new;
2486: my $resized;
2487: if (-e $img_path) {
2488: $ima->Read($img_path);
2489: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2490: my $width = $ima->Get('width');
2491: my $height = $ima->Get('height');
2492: if ($width > $resizewidth) {
2493: my $factor = $width/$resizewidth;
2494: my $newheight = $height/$factor;
2495: $ima->Scale(width=>$resizewidth,height=>$newheight);
2496: $resized = 1;
2497: }
2498: }
2499: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2500: my $width = $ima->Get('width');
2501: my $height = $ima->Get('height');
2502: if ($height > $resizeheight) {
2503: my $factor = $height/$resizeheight;
2504: my $newwidth = $width/$factor;
2505: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2506: $resized = 1;
2507: }
2508: }
2509: if ($resized) {
2510: $ima->Write($img_path);
2511: }
2512: }
2513: return;
1.977 amueller 2514: }
2515:
1.608 albertel 2516: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2517: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2518: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2519: # $context - possible values: coursedoc, existingfile, overwrite,
2520: # canceloverwrite, or ''.
2521: # if 'coursedoc': upload to the current course
2522: # if 'existingfile': write file to tmp/overwrites directory
2523: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2524: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2525: # $subdir - directory in userfile to store the file into
1.858 raeburn 2526: # $parser - instruction to parse file for objects ($parser = parse)
2527: # $allfiles - reference to hash for embedded objects
2528: # $codebase - reference to hash for codebase of java objects
2529: # $desuname - username for permanent storage of uploaded file
2530: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2531: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2532: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2533: # $resizewidth - width (pixels) to which to resize uploaded image
2534: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2535: # $mimetype - reference to scalar to accommodate mime type determined
2536: # from File::MMagic if $parser = parse.
1.858 raeburn 2537: #
1.686 albertel 2538: # output: url of file in userspace, or error: <message>
2539: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2540:
1.531 albertel 2541: sub userfileupload {
1.1090 raeburn 2542: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2543: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2544: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2545: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2546: $fname=&clean_filename($fname);
1.1090 raeburn 2547: # See if there is anything left
1.257 www 2548: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2549: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2550: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2551: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2552: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2553: my $now = time;
1.1090 raeburn 2554: my $filepath;
1.1095 raeburn 2555: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2556: $filepath = 'tmp/helprequests/'.$now;
2557: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2558: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2559: '_'.$env{'user.domain'}.'/pending';
2560: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2561: my ($docuname,$docudom);
2562: if ($destudom) {
2563: $docudom = $destudom;
2564: } else {
2565: $docudom = $env{'user.domain'};
2566: }
2567: if ($destuname) {
2568: $docuname = $destuname;
2569: } else {
2570: $docuname = $env{'user.name'};
2571: }
2572: if (exists($env{'form.group'})) {
2573: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2574: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2575: }
2576: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2577: if ($context eq 'canceloverwrite') {
2578: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2579: if (-e $tempfile) {
2580: my @info = stat($tempfile);
2581: if ($info[9] eq $env{'form.timestamp'}) {
2582: unlink($tempfile);
2583: }
2584: }
2585: return;
1.523 raeburn 2586: }
2587: }
1.1090 raeburn 2588: # Create the directory if not present
1.741 raeburn 2589: my @parts=split(/\//,$filepath);
2590: my $fullpath = $perlvar{'lonDaemons'};
2591: for (my $i=0;$i<@parts;$i++) {
2592: $fullpath .= '/'.$parts[$i];
2593: if ((-e $fullpath)!=1) {
2594: mkdir($fullpath,0777);
2595: }
2596: }
2597: open(my $fh,'>'.$fullpath.'/'.$fname);
2598: print $fh $env{'form.'.$formname};
2599: close($fh);
1.1090 raeburn 2600: if ($context eq 'existingfile') {
2601: my @info = stat($fullpath.'/'.$fname);
2602: return ($fullpath.'/'.$fname,$info[9]);
2603: } else {
2604: return $fullpath.'/'.$fname;
2605: }
1.523 raeburn 2606: }
1.995 raeburn 2607: if ($subdir eq 'scantron') {
2608: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2609: } else {
1.995 raeburn 2610: $fname="$subdir/$fname";
2611: }
1.1090 raeburn 2612: if ($context eq 'coursedoc') {
1.638 albertel 2613: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2614: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2615: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2616: return &finishuserfileupload($docuname,$docudom,
2617: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2618: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2619: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2620: } else {
1.620 albertel 2621: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2622: return &process_coursefile('uploaddoc',$docuname,$docudom,
2623: $fname,$formname,$parser,
1.1095 raeburn 2624: $allfiles,$codebase,$mimetype);
1.481 raeburn 2625: }
1.719 banghart 2626: } elsif (defined($destuname)) {
2627: my $docuname=$destuname;
2628: my $docudom=$destudom;
1.860 raeburn 2629: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2630: $parser,$allfiles,$codebase,
1.1051 raeburn 2631: $thumbwidth,$thumbheight,
1.1095 raeburn 2632: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2633: } else {
1.638 albertel 2634: my $docuname=$env{'user.name'};
2635: my $docudom=$env{'user.domain'};
1.714 raeburn 2636: if (exists($env{'form.group'})) {
2637: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2638: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2639: }
1.860 raeburn 2640: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2641: $parser,$allfiles,$codebase,
1.1051 raeburn 2642: $thumbwidth,$thumbheight,
1.1095 raeburn 2643: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2644: }
1.271 www 2645: }
2646:
2647: sub finishuserfileupload {
1.860 raeburn 2648: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2649: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2650: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2651: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2652:
1.860 raeburn 2653: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2654: $file=$fname;
2655: if ($fname=~m|/|) {
2656: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2657: $path.=$fnamepath.'/';
2658: }
1.259 www 2659: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2660: my $count;
2661: for ($count=4;$count<=$#parts;$count++) {
2662: $filepath.="/$parts[$count]";
2663: if ((-e $filepath)!=1) {
2664: mkdir($filepath,0777);
2665: }
2666: }
1.984 neumanie 2667:
1.258 www 2668: # Save the file
2669: {
1.701 albertel 2670: if (!open(FH,'>'.$filepath.'/'.$file)) {
2671: &logthis('Failed to create '.$filepath.'/'.$file);
2672: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2673: return '/adm/notfound.html';
2674: }
1.1090 raeburn 2675: if ($context eq 'overwrite') {
1.1117 foxr 2676: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2677: my $target = $filepath.'/'.$file;
2678: if (-e $source) {
2679: my @info = stat($source);
2680: if ($info[9] eq $env{'form.timestamp'}) {
2681: unless (&File::Copy::move($source,$target)) {
2682: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2683: return "Moving from $source failed";
2684: }
2685: } else {
2686: return "Temporary file: $source had unexpected date/time for last modification";
2687: }
2688: } else {
2689: return "Temporary file: $source missing";
2690: }
2691: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2692: &logthis('Failed to write to '.$filepath.'/'.$file);
2693: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2694: return '/adm/notfound.html';
2695: }
1.570 albertel 2696: close(FH);
1.1051 raeburn 2697: if ($resizewidth && $resizeheight) {
2698: my $mm = new File::MMagic;
2699: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2700: if ($mime_type =~ m{^image/}) {
2701: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2702: }
1.977 amueller 2703: }
1.258 www 2704: }
1.637 raeburn 2705: if ($parser eq 'parse') {
1.1024 raeburn 2706: my $mm = new File::MMagic;
1.1095 raeburn 2707: my $type = $mm->checktype_filename($filepath.'/'.$file);
2708: if ($type eq 'text/html') {
1.1024 raeburn 2709: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2710: $allfiles,$codebase);
2711: unless ($parse_result eq 'ok') {
2712: &logthis('Failed to parse '.$filepath.$file.
2713: ' for embedded media: '.$parse_result);
2714: }
1.637 raeburn 2715: }
1.1095 raeburn 2716: if (ref($mimetype)) {
2717: $$mimetype = $type;
2718: }
1.637 raeburn 2719: }
1.860 raeburn 2720: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2721: my $input = $filepath.'/'.$file;
2722: my $output = $filepath.'/'.'tn-'.$file;
2723: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2724: system("convert -sample $thumbsize $input $output");
2725: if (-e $filepath.'/'.'tn-'.$file) {
2726: $fetchthumb = 1;
2727: }
2728: }
1.858 raeburn 2729:
1.259 www 2730: # Notify homeserver to grep it
2731: #
1.984 neumanie 2732: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2733: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2734: if ($fetchresult eq 'ok') {
1.860 raeburn 2735: if ($fetchthumb) {
2736: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2737: if ($thumbresult ne 'ok') {
2738: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2739: $docuhome.': '.$thumbresult);
2740: }
2741: }
1.259 www 2742: #
1.258 www 2743: # Return the URL to it
1.494 albertel 2744: return '/uploaded/'.$path.$file;
1.263 www 2745: } else {
1.494 albertel 2746: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2747: ': '.$fetchresult);
1.263 www 2748: return '/adm/notfound.html';
1.858 raeburn 2749: }
1.493 albertel 2750: }
2751:
1.637 raeburn 2752: sub extract_embedded_items {
1.961 raeburn 2753: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2754: my @state = ();
2755: my %javafiles = (
2756: codebase => '',
2757: code => '',
2758: archive => ''
2759: );
2760: my %mediafiles = (
2761: src => '',
2762: movie => '',
2763: );
1.648 raeburn 2764: my $p;
2765: if ($content) {
2766: $p = HTML::LCParser->new($content);
2767: } else {
1.961 raeburn 2768: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2769: }
1.641 albertel 2770: while (my $t=$p->get_token()) {
1.640 albertel 2771: if ($t->[0] eq 'S') {
2772: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2773: push(@state, $tagname);
1.648 raeburn 2774: if (lc($tagname) eq 'allow') {
2775: &add_filetype($allfiles,$attr->{'src'},'src');
2776: }
1.640 albertel 2777: if (lc($tagname) eq 'img') {
2778: &add_filetype($allfiles,$attr->{'src'},'src');
2779: }
1.886 albertel 2780: if (lc($tagname) eq 'a') {
2781: &add_filetype($allfiles,$attr->{'href'},'href');
2782: }
1.645 raeburn 2783: if (lc($tagname) eq 'script') {
2784: if ($attr->{'archive'} =~ /\.jar$/i) {
2785: &add_filetype($allfiles,$attr->{'archive'},'archive');
2786: } else {
2787: &add_filetype($allfiles,$attr->{'src'},'src');
2788: }
2789: }
2790: if (lc($tagname) eq 'link') {
2791: if (lc($attr->{'rel'}) eq 'stylesheet') {
2792: &add_filetype($allfiles,$attr->{'href'},'href');
2793: }
2794: }
1.640 albertel 2795: if (lc($tagname) eq 'object' ||
2796: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2797: foreach my $item (keys(%javafiles)) {
2798: $javafiles{$item} = '';
2799: }
2800: }
2801: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2802: my $name = lc($attr->{'name'});
2803: foreach my $item (keys(%javafiles)) {
2804: if ($name eq $item) {
2805: $javafiles{$item} = $attr->{'value'};
2806: last;
2807: }
2808: }
2809: foreach my $item (keys(%mediafiles)) {
2810: if ($name eq $item) {
2811: &add_filetype($allfiles, $attr->{'value'}, 'value');
2812: last;
2813: }
2814: }
2815: }
2816: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2817: foreach my $item (keys(%javafiles)) {
2818: if ($attr->{$item}) {
2819: $javafiles{$item} = $attr->{$item};
2820: last;
2821: }
2822: }
2823: foreach my $item (keys(%mediafiles)) {
2824: if ($attr->{$item}) {
2825: &add_filetype($allfiles,$attr->{$item},$item);
2826: last;
2827: }
2828: }
2829: }
2830: } elsif ($t->[0] eq 'E') {
2831: my ($tagname) = ($t->[1]);
2832: if ($javafiles{'codebase'} ne '') {
2833: $javafiles{'codebase'} .= '/';
2834: }
2835: if (lc($tagname) eq 'applet' ||
2836: lc($tagname) eq 'object' ||
2837: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2838: ) {
2839: foreach my $item (keys(%javafiles)) {
2840: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2841: my $file=$javafiles{'codebase'}.$javafiles{$item};
2842: &add_filetype($allfiles,$file,$item);
2843: }
2844: }
2845: }
2846: pop @state;
2847: }
2848: }
1.637 raeburn 2849: return 'ok';
2850: }
2851:
1.639 albertel 2852: sub add_filetype {
2853: my ($allfiles,$file,$type)=@_;
2854: if (exists($allfiles->{$file})) {
2855: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2856: push(@{$allfiles->{$file}}, &escape($type));
2857: }
2858: } else {
2859: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2860: }
2861: }
2862:
1.493 albertel 2863: sub removeuploadedurl {
1.984 neumanie 2864: my ($url)=@_;
2865: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2866: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2867: }
2868:
2869: sub removeuserfile {
2870: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2871: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2872: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2873: if ($result eq 'ok') {
1.798 raeburn 2874: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2875: my $metafile = $fname.'.meta';
2876: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2877: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2878: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2879: my $sqlresult =
1.823 albertel 2880: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2881: 'portfolio_metadata',$group,
2882: 'delete');
1.798 raeburn 2883: }
2884: }
2885: return $result;
1.257 www 2886: }
1.15 www 2887:
1.530 albertel 2888: sub mkdiruserfile {
2889: my ($docuname,$docudom,$dir)=@_;
2890: my $home=&homeserver($docuname,$docudom);
2891: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2892: }
2893:
1.531 albertel 2894: sub renameuserfile {
2895: my ($docuname,$docudom,$old,$new)=@_;
2896: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2897: my $result = &reply("renameuserfile:$docudom:$docuname:".
2898: &escape("$old").':'.&escape("$new"),$home);
2899: if ($result eq 'ok') {
2900: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2901: my $oldmeta = $old.'.meta';
2902: my $newmeta = $new.'.meta';
2903: my $metaresult =
2904: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2905: my $url = "/uploaded/$docudom/$docuname/$old";
2906: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2907: my $sqlresult =
1.823 albertel 2908: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2909: 'portfolio_metadata',$group,
2910: 'delete');
1.798 raeburn 2911: }
2912: }
2913: return $result;
1.531 albertel 2914: }
2915:
1.14 www 2916: # ------------------------------------------------------------------------- Log
2917:
2918: sub log {
2919: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2920: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2921: }
2922:
2923: # ------------------------------------------------------------------ Course Log
1.352 www 2924: #
2925: # This routine flushes several buffers of non-mission-critical nature
2926: #
1.157 www 2927:
2928: sub flushcourselogs {
1.352 www 2929: &logthis('Flushing log buffers');
2930: #
2931: # course logs
2932: # This is a log of all transactions in a course, which can be used
2933: # for data mining purposes
2934: #
2935: # It also collects the courseid database, which lists last transaction
2936: # times and course titles for all courseids
2937: #
2938: my %courseidbuffer=();
1.921 raeburn 2939: foreach my $crsid (keys(%courselogs)) {
1.352 www 2940: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2941: &escape($courselogs{$crsid}),
2942: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2943: delete $courselogs{$crsid};
2944: } else {
2945: &logthis('Failed to flush log buffer for '.$crsid);
2946: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2947: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2948: " exceeded maximum size, deleting.</font>");
2949: delete $courselogs{$crsid};
2950: }
1.352 www 2951: }
1.920 raeburn 2952: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2953: 'description' => $coursedescrbuf{$crsid},
2954: 'inst_code' => $courseinstcodebuf{$crsid},
2955: 'type' => $coursetypebuf{$crsid},
2956: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2957: };
1.191 harris41 2958: }
1.352 www 2959: #
2960: # Write course id database (reverse lookup) to homeserver of courses
2961: # Is used in pickcourse
2962: #
1.840 albertel 2963: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2964: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2965: $courseidbuffer{$crs_home},
2966: $crs_home,'timeonly');
1.352 www 2967: }
2968: #
2969: # File accesses
2970: # Writes to the dynamic metadata of resources to get hit counts, etc.
2971: #
1.449 matthew 2972: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2973: if ($entry =~ /___count$/) {
2974: my ($dom,$name);
1.807 albertel 2975: ($dom,$name,undef)=
1.811 albertel 2976: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2977: if (! defined($dom) || $dom eq '' ||
2978: ! defined($name) || $name eq '') {
1.620 albertel 2979: my $cid = $env{'request.course.id'};
2980: $dom = $env{'request.'.$cid.'.domain'};
2981: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2982: }
1.450 matthew 2983: my $value = $accesshash{$entry};
2984: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2985: my %temphash=($url => $value);
1.449 matthew 2986: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2987: if ($result eq 'ok') {
2988: delete $accesshash{$entry};
2989: } elsif ($result eq 'unknown_cmd') {
2990: # Target server has old code running on it.
1.450 matthew 2991: my %temphash=($entry => $value);
1.449 matthew 2992: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2993: delete $accesshash{$entry};
2994: }
2995: }
2996: } else {
1.811 albertel 2997: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2998: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2999: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3000: delete $accesshash{$entry};
3001: }
1.185 www 3002: }
1.191 harris41 3003: }
1.352 www 3004: #
3005: # Roles
3006: # Reverse lookup of user roles for course faculty/staff and co-authorship
3007: #
1.800 albertel 3008: foreach my $entry (keys(%userrolehash)) {
1.351 www 3009: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3010: split(/\:/,$entry);
3011: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3012: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3013: $rudom,$runame) eq 'ok') {
3014: delete $userrolehash{$entry};
3015: }
3016: }
1.662 raeburn 3017: #
3018: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3019: #
3020: my %domrolebuffer = ();
1.1000 raeburn 3021: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3022: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3023: if ($domrolebuffer{$rudom}) {
3024: $domrolebuffer{$rudom}.='&'.&escape($entry).
3025: '='.&escape($domainrolehash{$entry});
3026: } else {
3027: $domrolebuffer{$rudom}.=&escape($entry).
3028: '='.&escape($domainrolehash{$entry});
3029: }
3030: delete $domainrolehash{$entry};
3031: }
3032: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3033: my %servers = &get_servers($dom,'library');
3034: foreach my $tryserver (keys(%servers)) {
3035: unless (&reply('domroleput:'.$dom.':'.
3036: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3037: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3038: }
1.662 raeburn 3039: }
3040: }
1.186 www 3041: $dumpcount++;
1.157 www 3042: }
3043:
3044: sub courselog {
3045: my $what=shift;
1.158 www 3046: $what=time.':'.$what;
1.620 albertel 3047: unless ($env{'request.course.id'}) { return ''; }
3048: $coursedombuf{$env{'request.course.id'}}=
3049: $env{'course.'.$env{'request.course.id'}.'.domain'};
3050: $coursenumbuf{$env{'request.course.id'}}=
3051: $env{'course.'.$env{'request.course.id'}.'.num'};
3052: $coursehombuf{$env{'request.course.id'}}=
3053: $env{'course.'.$env{'request.course.id'}.'.home'};
3054: $coursedescrbuf{$env{'request.course.id'}}=
3055: $env{'course.'.$env{'request.course.id'}.'.description'};
3056: $courseinstcodebuf{$env{'request.course.id'}}=
3057: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3058: $courseownerbuf{$env{'request.course.id'}}=
3059: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3060: $coursetypebuf{$env{'request.course.id'}}=
3061: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3062: if (defined $courselogs{$env{'request.course.id'}}) {
3063: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3064: } else {
1.620 albertel 3065: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3066: }
1.620 albertel 3067: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3068: &flushcourselogs();
3069: }
1.158 www 3070: }
3071:
3072: sub courseacclog {
3073: my $fnsymb=shift;
1.620 albertel 3074: unless ($env{'request.course.id'}) { return ''; }
3075: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 3076: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 3077: $what.=':POST';
1.583 matthew 3078: # FIXME: Probably ought to escape things....
1.800 albertel 3079: foreach my $key (keys(%env)) {
3080: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3081: my $formitem = $1;
3082: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3083: $what.=':'.$formitem.'='.$env{$key};
3084: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3085: $what.=':'.$formitem.'='.$env{$key};
3086: }
1.158 www 3087: }
1.191 harris41 3088: }
1.583 matthew 3089: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3090: # FIXME: We should not be depending on a form parameter that someone
3091: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3092: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3093: $what.= ':POST';
3094: # FIXME: Probably ought to escape things....
3095: foreach my $element ('courseexp','crsfulltext','crsrelated',
3096: 'crsdiscuss') {
1.620 albertel 3097: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3098: }
3099: }
1.158 www 3100: }
3101: &courselog($what);
1.149 www 3102: }
3103:
1.185 www 3104: sub countacc {
3105: my $url=&declutter(shift);
1.458 matthew 3106: return if (! defined($url) || $url eq '');
1.620 albertel 3107: unless ($env{'request.course.id'}) { return ''; }
3108: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3109: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3110: $accesshash{$key}++;
1.185 www 3111: }
1.349 www 3112:
1.361 www 3113: sub linklog {
3114: my ($from,$to)=@_;
3115: $from=&declutter($from);
3116: $to=&declutter($to);
3117: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3118: $accesshash{$to.'___'.$from.'___goto'}=1;
3119: }
3120:
1.349 www 3121: sub userrolelog {
3122: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3123: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3124: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3125: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3126: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3127: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3128: $userrolehash
3129: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3130: =$tend.':'.$tstart;
1.662 raeburn 3131: }
1.898 albertel 3132: if (($env{'request.role'} =~ /dc\./) &&
3133: (($trole=~/^au/) || ($trole=~/^in/) ||
3134: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3135: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3136: ($trole=~/^co/))) {
1.898 albertel 3137: $userrolehash
3138: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3139: =$tend.':'.$tstart;
3140: }
1.662 raeburn 3141: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3142: ($trole=~/^li/) || ($trole=~/^li/) ||
3143: ($trole=~/^au/) || ($trole=~/^dg/) ||
3144: ($trole=~/^sc/)) {
3145: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3146: $domainrolehash
3147: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3148: = $tend.':'.$tstart;
3149: }
1.351 www 3150: }
3151:
1.957 raeburn 3152: sub courserolelog {
3153: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3154: if (($trole eq 'cc') || ($trole eq 'in') ||
3155: ($trole eq 'ep') || ($trole eq 'ad') ||
3156: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3157: ($trole=~/^cr/) || ($trole eq 'gr') ||
3158: ($trole eq 'co')) {
1.957 raeburn 3159: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3160: my $cdom = $1;
3161: my $cnum = $2;
3162: my $sec = $3;
3163: my $namespace = 'rolelog';
3164: my %storehash = (
3165: role => $trole,
3166: start => $tstart,
3167: end => $tend,
3168: selfenroll => $selfenroll,
3169: context => $context,
3170: );
3171: if ($trole eq 'gr') {
3172: $namespace = 'groupslog';
3173: $storehash{'group'} = $sec;
3174: } else {
3175: $storehash{'section'} = $sec;
3176: }
3177: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3178: if (($trole ne 'st') || ($sec ne '')) {
3179: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3180: }
1.957 raeburn 3181: }
3182: }
3183: return;
3184: }
3185:
1.351 www 3186: sub get_course_adv_roles {
1.948 raeburn 3187: my ($cid,$codes) = @_;
1.620 albertel 3188: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3189: my %coursehash=&coursedescription($cid);
1.988 raeburn 3190: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3191: my %nothide=();
1.800 albertel 3192: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3193: if ($user !~ /:/) {
3194: $nothide{join(':',split(/[\@]/,$user))}=1;
3195: } else {
3196: $nothide{$user}=1;
3197: }
1.470 www 3198: }
1.351 www 3199: my %returnhash=();
3200: my %dumphash=
3201: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3202: my $now=time;
1.997 raeburn 3203: my %privileged;
1.1000 raeburn 3204: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3205: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3206: if (($tstart) && ($tstart<0)) { next; }
3207: if (($tend) && ($tend<$now)) { next; }
3208: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3209: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3210: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3211: unless (ref($privileged{$domain}) eq 'HASH') {
3212: my %dompersonnel =
1.998 raeburn 3213: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3214: $privileged{$domain} = {};
3215: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3216: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3217: foreach my $user (keys(%{$dompersonnel{$server}})) {
3218: my ($trole,$uname,$udom) = split(/:/,$user);
3219: $privileged{$udom}{$uname} = 1;
3220: }
3221: }
3222: }
3223: }
3224: if ((exists($privileged{$domain}{$username})) &&
3225: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3226: if ($role eq 'cr') { next; }
1.948 raeburn 3227: if ($codes) {
3228: if ($section) { $role .= ':'.$section; }
3229: if ($returnhash{$role}) {
3230: $returnhash{$role}.=','.$username.':'.$domain;
3231: } else {
3232: $returnhash{$role}=$username.':'.$domain;
3233: }
1.351 www 3234: } else {
1.988 raeburn 3235: my $key=&plaintext($role,$crstype);
1.973 bisitz 3236: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3237: if ($returnhash{$key}) {
3238: $returnhash{$key}.=','.$username.':'.$domain;
3239: } else {
3240: $returnhash{$key}=$username.':'.$domain;
3241: }
1.351 www 3242: }
1.948 raeburn 3243: }
1.400 www 3244: return %returnhash;
3245: }
3246:
3247: sub get_my_roles {
1.937 raeburn 3248: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3249: unless (defined($uname)) { $uname=$env{'user.name'}; }
3250: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3251: my (%dumphash,%nothide);
1.1086 raeburn 3252: if ($context eq 'userroles') {
3253: my $extra = &freeze_escape({'skipcheck' => 1});
3254: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3255: } else {
3256: %dumphash=
1.400 www 3257: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3258: if ($hidepriv) {
3259: my %coursehash=&coursedescription($udom.'_'.$uname);
3260: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3261: if ($user !~ /:/) {
3262: $nothide{join(':',split(/[\@]/,$user))} = 1;
3263: } else {
3264: $nothide{$user} = 1;
3265: }
3266: }
3267: }
1.858 raeburn 3268: }
1.400 www 3269: my %returnhash=();
3270: my $now=time;
1.999 raeburn 3271: my %privileged;
1.800 albertel 3272: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3273: my ($role,$tend,$tstart);
3274: if ($context eq 'userroles') {
3275: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3276: } else {
3277: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3278: }
1.400 www 3279: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3280: my $status = 'active';
1.939 raeburn 3281: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3282: $status = 'previous';
3283: }
3284: if (($tstart) && ($now<$tstart)) {
3285: $status = 'future';
3286: }
3287: if (ref($types) eq 'ARRAY') {
3288: if (!grep(/^\Q$status\E$/,@{$types})) {
3289: next;
3290: }
3291: } else {
3292: if ($status ne 'active') {
3293: next;
3294: }
3295: }
1.867 raeburn 3296: my ($rolecode,$username,$domain,$section,$area);
3297: if ($context eq 'userroles') {
3298: ($area,$rolecode) = split(/_/,$entry);
3299: (undef,$domain,$username,$section) = split(/\//,$area);
3300: } else {
3301: ($role,$username,$domain,$section) = split(/\:/,$entry);
3302: }
1.832 raeburn 3303: if (ref($roledoms) eq 'ARRAY') {
3304: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3305: next;
3306: }
3307: }
3308: if (ref($roles) eq 'ARRAY') {
3309: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3310: if ($role =~ /^cr\//) {
3311: if (!grep(/^cr$/,@{$roles})) {
3312: next;
3313: }
1.1104 raeburn 3314: } elsif ($role =~ /^gr\//) {
3315: if (!grep(/^gr$/,@{$roles})) {
3316: next;
3317: }
1.922 raeburn 3318: } else {
3319: next;
3320: }
1.832 raeburn 3321: }
1.867 raeburn 3322: }
1.937 raeburn 3323: if ($hidepriv) {
1.999 raeburn 3324: if ($context eq 'userroles') {
3325: if ((&privileged($username,$domain)) &&
3326: (!$nothide{$username.':'.$domain})) {
3327: next;
3328: }
3329: } else {
3330: unless (ref($privileged{$domain}) eq 'HASH') {
3331: my %dompersonnel =
3332: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3333: $privileged{$domain} = {};
3334: if (keys(%dompersonnel)) {
3335: foreach my $server (keys(%dompersonnel)) {
3336: if (ref($dompersonnel{$server}) eq 'HASH') {
3337: foreach my $user (keys(%{$dompersonnel{$server}})) {
3338: my ($trole,$uname,$udom) = split(/:/,$user);
3339: $privileged{$udom}{$uname} = $trole;
3340: }
3341: }
3342: }
3343: }
3344: }
3345: if (exists($privileged{$domain}{$username})) {
3346: if (!$nothide{$username.':'.$domain}) {
3347: next;
3348: }
3349: }
1.937 raeburn 3350: }
3351: }
1.933 raeburn 3352: if ($withsec) {
3353: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3354: $tstart.':'.$tend;
3355: } else {
3356: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3357: }
1.832 raeburn 3358: }
1.373 www 3359: return %returnhash;
1.399 www 3360: }
3361:
3362: # ----------------------------------------------------- Frontpage Announcements
3363: #
3364: #
3365:
3366: sub postannounce {
3367: my ($server,$text)=@_;
1.844 albertel 3368: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3369: unless ($text=~/\w/) { $text=''; }
3370: return &reply('setannounce:'.&escape($text),$server);
3371: }
3372:
3373: sub getannounce {
1.448 albertel 3374:
3375: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3376: my $announcement='';
1.800 albertel 3377: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3378: close($fh);
1.399 www 3379: if ($announcement=~/\w/) {
3380: return
3381: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3382: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3383: } else {
3384: return '';
3385: }
3386: } else {
3387: return '';
3388: }
1.351 www 3389: }
1.353 www 3390:
3391: # ---------------------------------------------------------- Course ID routines
3392: # Deal with domain's nohist_courseid.db files
3393: #
3394:
3395: sub courseidput {
1.921 raeburn 3396: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3397: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3398: my $outcome;
3399: if ($caller eq 'timeonly') {
3400: my $cids = '';
3401: foreach my $item (keys(%$storehash)) {
3402: $cids.=&escape($item).'&';
3403: }
3404: $cids=~s/\&$//;
3405: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3406: $coursehome);
3407: } else {
3408: my $items = '';
3409: foreach my $item (keys(%$storehash)) {
3410: $items.= &escape($item).'='.
3411: &freeze_escape($$storehash{$item}).'&';
3412: }
3413: $items=~s/\&$//;
3414: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3415: $coursehome);
1.918 raeburn 3416: }
3417: if ($outcome eq 'unknown_cmd') {
3418: my $what;
3419: foreach my $cid (keys(%$storehash)) {
3420: $what .= &escape($cid).'=';
1.921 raeburn 3421: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3422: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3423: }
3424: $what =~ s/\:$/&/;
3425: }
3426: $what =~ s/\&$//;
3427: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3428: } else {
3429: return $outcome;
3430: }
1.353 www 3431: }
3432:
3433: sub courseiddump {
1.921 raeburn 3434: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3435: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3436: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3437: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3438: my $as_hash = 1;
3439: my %returnhash;
3440: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3441: my %libserv = &all_library();
3442: foreach my $tryserver (keys(%libserv)) {
3443: if ( ( $hostidflag == 1
3444: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3445: || (!defined($hostidflag)) ) {
3446:
1.918 raeburn 3447: if (($domfilter eq '') ||
3448: (&host_domain($tryserver) eq $domfilter)) {
3449: my $rep =
3450: &reply('courseiddump:'.&host_domain($tryserver).':'.
3451: $sincefilter.':'.&escape($descfilter).':'.
3452: &escape($instcodefilter).':'.&escape($ownerfilter).
3453: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3454: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3455: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3456: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3457: &escape($cc_clone).':'.$cloneonly.':'.
3458: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3459: &escape($creationcontext).':'.$domcloner,
3460: $tryserver);
1.918 raeburn 3461: my @pairs=split(/\&/,$rep);
3462: foreach my $item (@pairs) {
3463: my ($key,$value)=split(/\=/,$item,2);
3464: $key = &unescape($key);
3465: next if ($key =~ /^error: 2 /);
3466: my $result = &thaw_unescape($value);
3467: if (ref($result) eq 'HASH') {
3468: $returnhash{$key}=$result;
3469: } else {
1.921 raeburn 3470: my @responses = split(/:/,$value);
3471: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3472: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3473: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3474: }
1.1008 raeburn 3475: }
1.353 www 3476: }
3477: }
3478: }
3479: }
3480: return %returnhash;
3481: }
3482:
1.1055 raeburn 3483: sub courselastaccess {
3484: my ($cdom,$cnum,$hostidref) = @_;
3485: my %returnhash;
3486: if ($cdom && $cnum) {
3487: my $chome = &homeserver($cnum,$cdom);
3488: if ($chome ne 'no_host') {
3489: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3490: &extract_lastaccess(\%returnhash,$rep);
3491: }
3492: } else {
3493: if (!$cdom) { $cdom=''; }
3494: my %libserv = &all_library();
3495: foreach my $tryserver (keys(%libserv)) {
3496: if (ref($hostidref) eq 'ARRAY') {
3497: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3498: }
3499: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3500: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3501: &extract_lastaccess(\%returnhash,$rep);
3502: }
3503: }
3504: }
3505: return %returnhash;
3506: }
3507:
3508: sub extract_lastaccess {
3509: my ($returnhash,$rep) = @_;
3510: if (ref($returnhash) eq 'HASH') {
3511: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3512: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3513: $rep eq '') {
3514: my @pairs=split(/\&/,$rep);
3515: foreach my $item (@pairs) {
3516: my ($key,$value)=split(/\=/,$item,2);
3517: $key = &unescape($key);
3518: next if ($key =~ /^error: 2 /);
3519: $returnhash->{$key} = &thaw_unescape($value);
3520: }
3521: }
3522: }
3523: return;
3524: }
3525:
1.658 raeburn 3526: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3527:
3528: sub dcmailput {
1.685 raeburn 3529: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3530: my $status = &Apache::lonnet::critical(
1.740 www 3531: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3532: &escape($message),$server);
1.662 raeburn 3533: return $status;
3534: }
3535:
1.658 raeburn 3536: sub dcmaildump {
3537: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3538: my %returnhash=();
1.846 albertel 3539:
3540: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3541: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3542: &escape($enddate).':';
3543: my @esc_senders=map { &escape($_)} @$senders;
3544: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3545: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3546: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3547: if (($key) && ($value)) {
3548: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3549: }
3550: }
3551: }
3552: return %returnhash;
3553: }
1.662 raeburn 3554: # ---------------------------------------------------------- Domain roles
3555:
3556: sub get_domain_roles {
3557: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3558: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3559: $startdate = '.';
3560: }
1.1018 raeburn 3561: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3562: $enddate = '.';
3563: }
1.922 raeburn 3564: my $rolelist;
3565: if (ref($roles) eq 'ARRAY') {
3566: $rolelist = join(':',@{$roles});
3567: }
1.662 raeburn 3568: my %personnel = ();
1.841 albertel 3569:
3570: my %servers = &get_servers($dom,'library');
3571: foreach my $tryserver (keys(%servers)) {
3572: %{$personnel{$tryserver}}=();
3573: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3574: &escape($startdate).':'.
3575: &escape($enddate).':'.
3576: &escape($rolelist), $tryserver))) {
3577: my ($key,$value) = split(/\=/,$line,2);
3578: if (($key) && ($value)) {
3579: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3580: }
3581: }
1.662 raeburn 3582: }
3583: return %personnel;
3584: }
1.658 raeburn 3585:
1.1057 www 3586: # ----------------------------------------------------------- Interval timing
1.149 www 3587:
1.504 albertel 3588: sub get_first_access {
3589: my ($type,$argsymb)=@_;
1.790 albertel 3590: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3591: if ($argsymb) { $symb=$argsymb; }
3592: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3593: if ($type eq 'course') {
3594: $res='course';
3595: } elsif ($type eq 'map') {
1.588 albertel 3596: $res=&symbread($map);
3597: } else {
3598: $res=$symb;
3599: }
3600: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3601: return $times{"$courseid\0$res"};
1.504 albertel 3602: }
3603:
3604: sub set_first_access {
3605: my ($type)=@_;
1.790 albertel 3606: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3607: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3608: if ($type eq 'course') {
3609: $res='course';
3610: } elsif ($type eq 'map') {
1.588 albertel 3611: $res=&symbread($map);
3612: } else {
3613: $res=$symb;
3614: }
3615: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3616: if (!$firstaccess) {
1.588 albertel 3617: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3618: }
3619: return 'already_set';
1.504 albertel 3620: }
3621:
1.110 www 3622: # --------------------------------------------- Set Expire Date for Spreadsheet
3623:
3624: sub expirespread {
3625: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3626: my $cid=$env{'request.course.id'};
1.110 www 3627: if ($cid) {
3628: my $now=time;
3629: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3630: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3631: $env{'course.'.$cid.'.num'}.
1.110 www 3632: ':nohist_expirationdates:'.
3633: &escape($key).'='.$now,
1.620 albertel 3634: $env{'course.'.$cid.'.home'})
1.110 www 3635: }
3636: return 'ok';
1.14 www 3637: }
3638:
1.109 www 3639: # ----------------------------------------------------- Devalidate Spreadsheets
3640:
3641: sub devalidate {
1.325 www 3642: my ($symb,$uname,$udom)=@_;
1.620 albertel 3643: my $cid=$env{'request.course.id'};
1.109 www 3644: if ($cid) {
1.391 matthew 3645: # delete the stored spreadsheets for
3646: # - the student level sheet of this user in course's homespace
3647: # - the assessment level sheet for this resource
3648: # for this user in user's homespace
1.553 albertel 3649: # - current conditional state info
1.325 www 3650: my $key=$uname.':'.$udom.':';
1.109 www 3651: my $status=
1.299 matthew 3652: &del('nohist_calculatedsheets',
1.391 matthew 3653: [$key.'studentcalc:'],
1.620 albertel 3654: $env{'course.'.$cid.'.domain'},
3655: $env{'course.'.$cid.'.num'})
1.133 albertel 3656: .' '.
3657: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3658: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3659: unless ($status eq 'ok ok') {
3660: &logthis('Could not devalidate spreadsheet '.
1.325 www 3661: $uname.' at '.$udom.' for '.
1.109 www 3662: $symb.': '.$status);
1.133 albertel 3663: }
1.553 albertel 3664: &delenv('user.state.'.$cid);
1.109 www 3665: }
3666: }
3667:
1.265 albertel 3668: sub get_scalar {
3669: my ($string,$end) = @_;
3670: my $value;
3671: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3672: $value = $1;
3673: } elsif ($$string =~ s/^([^&]*?)&//) {
3674: $value = $1;
3675: }
3676: return &unescape($value);
3677: }
3678:
3679: sub array2str {
3680: my (@array) = @_;
3681: my $result=&arrayref2str(\@array);
3682: $result=~s/^__ARRAY_REF__//;
3683: $result=~s/__END_ARRAY_REF__$//;
3684: return $result;
3685: }
3686:
1.204 albertel 3687: sub arrayref2str {
3688: my ($arrayref) = @_;
1.265 albertel 3689: my $result='__ARRAY_REF__';
1.204 albertel 3690: foreach my $elem (@$arrayref) {
1.265 albertel 3691: if(ref($elem) eq 'ARRAY') {
3692: $result.=&arrayref2str($elem).'&';
3693: } elsif(ref($elem) eq 'HASH') {
3694: $result.=&hashref2str($elem).'&';
3695: } elsif(ref($elem)) {
3696: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3697: } else {
3698: $result.=&escape($elem).'&';
3699: }
3700: }
3701: $result=~s/\&$//;
1.265 albertel 3702: $result .= '__END_ARRAY_REF__';
1.204 albertel 3703: return $result;
3704: }
3705:
1.168 albertel 3706: sub hash2str {
1.204 albertel 3707: my (%hash) = @_;
3708: my $result=&hashref2str(\%hash);
1.265 albertel 3709: $result=~s/^__HASH_REF__//;
3710: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3711: return $result;
3712: }
3713:
3714: sub hashref2str {
3715: my ($hashref)=@_;
1.265 albertel 3716: my $result='__HASH_REF__';
1.800 albertel 3717: foreach my $key (sort(keys(%$hashref))) {
3718: if (ref($key) eq 'ARRAY') {
3719: $result.=&arrayref2str($key).'=';
3720: } elsif (ref($key) eq 'HASH') {
3721: $result.=&hashref2str($key).'=';
3722: } elsif (ref($key)) {
1.265 albertel 3723: $result.='=';
1.800 albertel 3724: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3725: } else {
1.800 albertel 3726: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3727: }
3728:
1.800 albertel 3729: if(ref($hashref->{$key}) eq 'ARRAY') {
3730: $result.=&arrayref2str($hashref->{$key}).'&';
3731: } elsif(ref($hashref->{$key}) eq 'HASH') {
3732: $result.=&hashref2str($hashref->{$key}).'&';
3733: } elsif(ref($hashref->{$key})) {
1.265 albertel 3734: $result.='&';
1.800 albertel 3735: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3736: } else {
1.800 albertel 3737: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3738: }
3739: }
1.168 albertel 3740: $result=~s/\&$//;
1.265 albertel 3741: $result .= '__END_HASH_REF__';
1.168 albertel 3742: return $result;
3743: }
3744:
3745: sub str2hash {
1.265 albertel 3746: my ($string)=@_;
3747: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3748: return %$hash;
3749: }
3750:
3751: sub str2hashref {
1.168 albertel 3752: my ($string) = @_;
1.265 albertel 3753:
3754: my %hash;
3755:
3756: if($string !~ /^__HASH_REF__/) {
3757: if (! ($string eq '' || !defined($string))) {
3758: $hash{'error'}='Not hash reference';
3759: }
3760: return (\%hash, $string);
3761: }
3762:
3763: $string =~ s/^__HASH_REF__//;
3764:
3765: while($string !~ /^__END_HASH_REF__/) {
3766: #key
3767: my $key='';
3768: if($string =~ /^__HASH_REF__/) {
3769: ($key, $string)=&str2hashref($string);
3770: if(defined($key->{'error'})) {
3771: $hash{'error'}='Bad data';
3772: return (\%hash, $string);
3773: }
3774: } elsif($string =~ /^__ARRAY_REF__/) {
3775: ($key, $string)=&str2arrayref($string);
3776: if($key->[0] eq 'Array reference error') {
3777: $hash{'error'}='Bad data';
3778: return (\%hash, $string);
3779: }
3780: } else {
3781: $string =~ s/^(.*?)=//;
1.267 albertel 3782: $key=&unescape($1);
1.265 albertel 3783: }
3784: $string =~ s/^=//;
3785:
3786: #value
3787: my $value='';
3788: if($string =~ /^__HASH_REF__/) {
3789: ($value, $string)=&str2hashref($string);
3790: if(defined($value->{'error'})) {
3791: $hash{'error'}='Bad data';
3792: return (\%hash, $string);
3793: }
3794: } elsif($string =~ /^__ARRAY_REF__/) {
3795: ($value, $string)=&str2arrayref($string);
3796: if($value->[0] eq 'Array reference error') {
3797: $hash{'error'}='Bad data';
3798: return (\%hash, $string);
3799: }
3800: } else {
3801: $value=&get_scalar(\$string,'__END_HASH_REF__');
3802: }
3803: $string =~ s/^&//;
3804:
3805: $hash{$key}=$value;
1.204 albertel 3806: }
1.265 albertel 3807:
3808: $string =~ s/^__END_HASH_REF__//;
3809:
3810: return (\%hash, $string);
1.204 albertel 3811: }
3812:
3813: sub str2array {
1.265 albertel 3814: my ($string)=@_;
3815: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3816: return @$array;
3817: }
3818:
3819: sub str2arrayref {
1.204 albertel 3820: my ($string) = @_;
1.265 albertel 3821: my @array;
3822:
3823: if($string !~ /^__ARRAY_REF__/) {
3824: if (! ($string eq '' || !defined($string))) {
3825: $array[0]='Array reference error';
3826: }
3827: return (\@array, $string);
3828: }
3829:
3830: $string =~ s/^__ARRAY_REF__//;
3831:
3832: while($string !~ /^__END_ARRAY_REF__/) {
3833: my $value='';
3834: if($string =~ /^__HASH_REF__/) {
3835: ($value, $string)=&str2hashref($string);
3836: if(defined($value->{'error'})) {
3837: $array[0] ='Array reference error';
3838: return (\@array, $string);
3839: }
3840: } elsif($string =~ /^__ARRAY_REF__/) {
3841: ($value, $string)=&str2arrayref($string);
3842: if($value->[0] eq 'Array reference error') {
3843: $array[0] ='Array reference error';
3844: return (\@array, $string);
3845: }
3846: } else {
3847: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3848: }
3849: $string =~ s/^&//;
3850:
3851: push(@array, $value);
1.191 harris41 3852: }
1.265 albertel 3853:
3854: $string =~ s/^__END_ARRAY_REF__//;
3855:
3856: return (\@array, $string);
1.168 albertel 3857: }
3858:
1.167 albertel 3859: # -------------------------------------------------------------------Temp Store
3860:
1.168 albertel 3861: sub tmpreset {
3862: my ($symb,$namespace,$domain,$stuname) = @_;
3863: if (!$symb) {
3864: $symb=&symbread();
1.620 albertel 3865: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3866: }
3867: $symb=escape($symb);
3868:
1.620 albertel 3869: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3870: $namespace=~s/\//\_/g;
3871: $namespace=~s/\W//g;
3872:
1.620 albertel 3873: if (!$domain) { $domain=$env{'user.domain'}; }
3874: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3875: if ($domain eq 'public' && $stuname eq 'public') {
3876: $stuname=$ENV{'REMOTE_ADDR'};
3877: }
1.1117 foxr 3878: my $path=LONCAPA::tempdir();
1.168 albertel 3879: my %hash;
3880: if (tie(%hash,'GDBM_File',
3881: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3882: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3883: foreach my $key (keys(%hash)) {
1.180 albertel 3884: if ($key=~ /:$symb/) {
1.168 albertel 3885: delete($hash{$key});
3886: }
3887: }
3888: }
3889: }
3890:
1.167 albertel 3891: sub tmpstore {
1.168 albertel 3892: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3893:
3894: if (!$symb) {
3895: $symb=&symbread();
1.620 albertel 3896: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3897: }
3898: $symb=escape($symb);
3899:
3900: if (!$namespace) {
3901: # I don't think we would ever want to store this for a course.
3902: # it seems this will only be used if we don't have a course.
1.620 albertel 3903: #$namespace=$env{'request.course.id'};
1.168 albertel 3904: #if (!$namespace) {
1.620 albertel 3905: $namespace=$env{'request.state'};
1.168 albertel 3906: #}
3907: }
3908: $namespace=~s/\//\_/g;
3909: $namespace=~s/\W//g;
1.620 albertel 3910: if (!$domain) { $domain=$env{'user.domain'}; }
3911: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3912: if ($domain eq 'public' && $stuname eq 'public') {
3913: $stuname=$ENV{'REMOTE_ADDR'};
3914: }
1.168 albertel 3915: my $now=time;
3916: my %hash;
1.1117 foxr 3917: my $path=LONCAPA::tempdir();
1.168 albertel 3918: if (tie(%hash,'GDBM_File',
3919: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3920: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3921: $hash{"version:$symb"}++;
3922: my $version=$hash{"version:$symb"};
3923: my $allkeys='';
3924: foreach my $key (keys(%$storehash)) {
3925: $allkeys.=$key.':';
1.591 albertel 3926: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3927: }
3928: $hash{"$version:$symb:timestamp"}=$now;
3929: $allkeys.='timestamp';
3930: $hash{"$version:keys:$symb"}=$allkeys;
3931: if (untie(%hash)) {
3932: return 'ok';
3933: } else {
3934: return "error:$!";
3935: }
3936: } else {
3937: return "error:$!";
3938: }
3939: }
1.167 albertel 3940:
1.168 albertel 3941: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3942:
1.168 albertel 3943: sub tmprestore {
3944: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3945:
1.168 albertel 3946: if (!$symb) {
3947: $symb=&symbread();
1.620 albertel 3948: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3949: }
3950: $symb=escape($symb);
3951:
1.620 albertel 3952: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3953:
1.620 albertel 3954: if (!$domain) { $domain=$env{'user.domain'}; }
3955: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3956: if ($domain eq 'public' && $stuname eq 'public') {
3957: $stuname=$ENV{'REMOTE_ADDR'};
3958: }
1.168 albertel 3959: my %returnhash;
3960: $namespace=~s/\//\_/g;
3961: $namespace=~s/\W//g;
3962: my %hash;
1.1117 foxr 3963: my $path=LONCAPA::tempdir();
1.168 albertel 3964: if (tie(%hash,'GDBM_File',
3965: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3966: &GDBM_READER(),0640)) {
1.168 albertel 3967: my $version=$hash{"version:$symb"};
3968: $returnhash{'version'}=$version;
3969: my $scope;
3970: for ($scope=1;$scope<=$version;$scope++) {
3971: my $vkeys=$hash{"$scope:keys:$symb"};
3972: my @keys=split(/:/,$vkeys);
3973: my $key;
3974: $returnhash{"$scope:keys"}=$vkeys;
3975: foreach $key (@keys) {
1.591 albertel 3976: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3977: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3978: }
3979: }
1.168 albertel 3980: if (!(untie(%hash))) {
3981: return "error:$!";
3982: }
3983: } else {
3984: return "error:$!";
3985: }
3986: return %returnhash;
1.167 albertel 3987: }
3988:
1.9 www 3989: # ----------------------------------------------------------------------- Store
3990:
3991: sub store {
1.124 www 3992: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3993: my $home='';
3994:
1.168 albertel 3995: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3996:
1.213 www 3997: $symb=&symbclean($symb);
1.122 albertel 3998: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3999:
1.620 albertel 4000: if (!$domain) { $domain=$env{'user.domain'}; }
4001: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4002:
4003: &devalidate($symb,$stuname,$domain);
1.109 www 4004:
4005: $symb=escape($symb);
1.187 www 4006: if (!$namespace) {
1.620 albertel 4007: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4008: return '';
4009: }
4010: }
1.620 albertel 4011: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4012:
4013: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4014: $$storehash{'host'}=$perlvar{'lonHostID'};
4015:
1.12 www 4016: my $namevalue='';
1.800 albertel 4017: foreach my $key (keys(%$storehash)) {
4018: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4019: }
1.12 www 4020: $namevalue=~s/\&$//;
1.187 www 4021: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4022: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4023: }
4024:
1.47 www 4025: # -------------------------------------------------------------- Critical Store
4026:
4027: sub cstore {
1.124 www 4028: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4029: my $home='';
4030:
1.168 albertel 4031: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4032:
1.213 www 4033: $symb=&symbclean($symb);
1.122 albertel 4034: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4035:
1.620 albertel 4036: if (!$domain) { $domain=$env{'user.domain'}; }
4037: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4038:
4039: &devalidate($symb,$stuname,$domain);
1.109 www 4040:
4041: $symb=escape($symb);
1.187 www 4042: if (!$namespace) {
1.620 albertel 4043: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4044: return '';
4045: }
4046: }
1.620 albertel 4047: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4048:
4049: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4050: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4051:
1.47 www 4052: my $namevalue='';
1.800 albertel 4053: foreach my $key (keys(%$storehash)) {
4054: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4055: }
1.47 www 4056: $namevalue=~s/\&$//;
1.187 www 4057: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4058: return critical
4059: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4060: }
4061:
1.9 www 4062: # --------------------------------------------------------------------- Restore
4063:
4064: sub restore {
1.124 www 4065: my ($symb,$namespace,$domain,$stuname) = @_;
4066: my $home='';
4067:
1.168 albertel 4068: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4069:
1.122 albertel 4070: if (!$symb) {
4071: unless ($symb=escape(&symbread())) { return ''; }
4072: } else {
1.213 www 4073: $symb=&escape(&symbclean($symb));
1.122 albertel 4074: }
1.188 www 4075: if (!$namespace) {
1.620 albertel 4076: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4077: return '';
4078: }
4079: }
1.620 albertel 4080: if (!$domain) { $domain=$env{'user.domain'}; }
4081: if (!$stuname) { $stuname=$env{'user.name'}; }
4082: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4083: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4084:
1.12 www 4085: my %returnhash=();
1.800 albertel 4086: foreach my $line (split(/\&/,$answer)) {
4087: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4088: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4089: }
1.75 www 4090: my $version;
4091: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4092: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4093: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4094: }
1.75 www 4095: }
1.13 www 4096: return %returnhash;
1.34 www 4097: }
4098:
4099: # ---------------------------------------------------------- Course Description
1.1118 foxr 4100: #
4101: #
1.34 www 4102:
4103: sub coursedescription {
1.731 albertel 4104: my ($courseid,$args)=@_;
1.34 www 4105: $courseid=~s/^\///;
1.49 www 4106: $courseid=~s/\_/\//g;
1.34 www 4107: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4108: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4109: my $normalid=$cdomain.'_'.$cnum;
4110: # need to always cache even if we get errors otherwise we keep
4111: # trying and trying and trying to get the course description.
4112: my %envhash=();
4113: my %returnhash=();
1.731 albertel 4114:
4115: my $expiretime=600;
4116: if ($env{'request.course.id'} eq $normalid) {
4117: $expiretime=120;
4118: }
4119:
4120: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4121: if (!$args->{'freshen_cache'}
4122: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4123: foreach my $key (keys(%env)) {
4124: next if ($key !~ /^\Q$prefix\E(.*)/);
4125: my ($setting) = $1;
4126: $returnhash{$setting} = $env{$key};
4127: }
4128: return %returnhash;
4129: }
4130:
1.1118 foxr 4131: # get the data again
4132:
1.731 albertel 4133: if (!$args->{'one_time'}) {
4134: $envhash{'course.'.$normalid.'.last_cache'}=time;
4135: }
1.811 albertel 4136:
1.34 www 4137: if ($chome ne 'no_host') {
1.302 albertel 4138: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4139: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4140: my $username = $env{'user.name'}; # Defult username
4141: if(defined $args->{'user'}) {
4142: $username = $args->{'user'};
4143: }
1.129 albertel 4144: $returnhash{'home'}= $chome;
4145: $returnhash{'domain'} = $cdomain;
4146: $returnhash{'num'} = $cnum;
1.741 raeburn 4147: if (!defined($returnhash{'type'})) {
4148: $returnhash{'type'} = 'Course';
4149: }
1.130 albertel 4150: while (my ($name,$value) = each %returnhash) {
1.53 www 4151: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4152: }
1.270 www 4153: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4154: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4155: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4156: $envhash{'course.'.$normalid.'.home'}=$chome;
4157: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4158: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4159: }
4160: }
1.731 albertel 4161: if (!$args->{'one_time'}) {
1.949 raeburn 4162: &appenv(\%envhash);
1.731 albertel 4163: }
1.302 albertel 4164: return %returnhash;
1.461 www 4165: }
4166:
1.1080 raeburn 4167: sub update_released_required {
4168: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4169: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4170: $cid = $env{'request.course.id'};
4171: $cdom = $env{'course.'.$cid.'.domain'};
4172: $cnum = $env{'course.'.$cid.'.num'};
4173: $chome = $env{'course.'.$cid.'.home'};
4174: }
4175: if ($needsrelease) {
4176: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4177: my $needsupdate;
4178: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4179: $needsupdate = 1;
4180: } else {
4181: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4182: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4183: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4184: $needsupdate = 1;
4185: }
4186: }
4187: if ($needsupdate) {
4188: my %needshash = (
4189: 'internal.releaserequired' => $needsrelease,
4190: );
4191: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4192: if ($putresult eq 'ok') {
4193: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4194: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4195: if (ref($crsinfo{$cid}) eq 'HASH') {
4196: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4197: &courseidput($cdom,\%crsinfo,$chome,'notime');
4198: }
4199: }
4200: }
4201: }
4202: return;
4203: }
4204:
1.461 www 4205: # -------------------------------------------------See if a user is privileged
4206:
4207: sub privileged {
4208: my ($username,$domain)=@_;
4209: my $rolesdump=&reply("dump:$domain:$username:roles",
4210: &homeserver($username,$domain));
1.1033 raeburn 4211: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4212: ($rolesdump =~ /^error:/)) {
4213: return 0;
4214: }
1.461 www 4215: my $now=time;
4216: if ($rolesdump ne '') {
1.800 albertel 4217: foreach my $entry (split(/&/,$rolesdump)) {
4218: if ($entry!~/^rolesdef_/) {
4219: my ($area,$role)=split(/=/,$entry);
1.461 www 4220: $area=~s/\_\w\w$//;
4221: my ($trole,$tend,$tstart)=split(/_/,$role);
4222: if (($trole eq 'dc') || ($trole eq 'su')) {
4223: my $active=1;
4224: if ($tend) {
4225: if ($tend<$now) { $active=0; }
4226: }
4227: if ($tstart) {
4228: if ($tstart>$now) { $active=0; }
4229: }
4230: if ($active) { return 1; }
4231: }
4232: }
4233: }
4234: }
4235: return 0;
1.9 www 4236: }
1.1 albertel 4237:
1.103 harris41 4238: # -------------------------------------------------------- Get user privileges
1.11 www 4239:
4240: sub rolesinit {
4241: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4242: my $now=time;
4243: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4244: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4245: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4246: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4247: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4248: return \%userroles;
4249: }
1.11 www 4250: my %allroles=();
1.678 raeburn 4251: my %allgroups=();
1.11 www 4252:
4253: if ($rolesdump ne '') {
1.800 albertel 4254: foreach my $entry (split(/&/,$rolesdump)) {
4255: if ($entry!~/^rolesdef_/) {
4256: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4257: $area=~s/\_\w\w$//;
1.678 raeburn 4258: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4259: if ($role=~/^cr/) {
1.807 albertel 4260: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4261: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4262: ($tend,$tstart)=split('_',$trest);
4263: } else {
4264: $trole=$role;
4265: }
1.678 raeburn 4266: } elsif ($role =~ m|^gr/|) {
4267: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4268: next if ($tstart eq '-1');
1.678 raeburn 4269: ($trole,$group_privs) = split(/\//,$trole);
4270: $group_privs = &unescape($group_privs);
1.587 albertel 4271: } else {
4272: ($trole,$tend,$tstart)=split(/_/,$role);
4273: }
1.743 albertel 4274: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4275: $username);
4276: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4277: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4278: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4279: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4280: my $spec=$trole.'.'.$area;
4281: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4282: if ($trole =~ /^cr\//) {
1.567 raeburn 4283: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4284: } elsif ($trole eq 'gr') {
4285: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4286: } else {
1.567 raeburn 4287: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4288: }
1.12 www 4289: }
1.662 raeburn 4290: }
1.191 harris41 4291: }
1.743 albertel 4292: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4293: $userroles{'user.adv'} = $adv;
4294: $userroles{'user.author'} = $author;
1.620 albertel 4295: $env{'user.adv'}=$adv;
1.11 www 4296: }
1.743 albertel 4297: return \%userroles;
1.11 www 4298: }
4299:
1.567 raeburn 4300: sub set_arearole {
4301: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4302: # log the associated role with the area
4303: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4304: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4305: }
4306:
4307: sub custom_roleprivs {
4308: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4309: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4310: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4311: if (&hostname($homsvr) ne '') {
1.567 raeburn 4312: my ($rdummy,$roledef)=
4313: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4314: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4315: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4316: if (defined($syspriv)) {
1.1043 raeburn 4317: if ($trest =~ /^$match_community$/) {
4318: $syspriv =~ s/bre\&S//;
4319: }
1.567 raeburn 4320: $$allroles{'cm./'}.=':'.$syspriv;
4321: $$allroles{$spec.'./'}.=':'.$syspriv;
4322: }
4323: if ($tdomain ne '') {
4324: if (defined($dompriv)) {
4325: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4326: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4327: }
4328: if (($trest ne '') && (defined($coursepriv))) {
4329: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4330: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4331: }
4332: }
4333: }
4334: }
4335: }
4336:
1.678 raeburn 4337: sub group_roleprivs {
4338: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4339: my $access = 1;
4340: my $now = time;
4341: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4342: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4343: if ($access) {
1.811 albertel 4344: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4345: $$allgroups{$course}{$group} .=':'.$group_privs;
4346: }
4347: }
1.567 raeburn 4348:
4349: sub standard_roleprivs {
4350: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4351: if (defined($pr{$trole.':s'})) {
4352: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4353: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4354: }
4355: if ($tdomain ne '') {
4356: if (defined($pr{$trole.':d'})) {
4357: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4358: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4359: }
4360: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4361: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4362: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4363: }
4364: }
4365: }
4366:
4367: sub set_userprivs {
1.1064 raeburn 4368: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4369: my $author=0;
4370: my $adv=0;
1.678 raeburn 4371: my %grouproles = ();
4372: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4373: my @groupkeys;
1.1000 raeburn 4374: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4375: push(@groupkeys,$role);
4376: }
4377: if (ref($groups_roles) eq 'HASH') {
4378: foreach my $key (keys(%{$groups_roles})) {
4379: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4380: push(@groupkeys,$key);
4381: }
4382: }
4383: }
4384: if (@groupkeys > 0) {
4385: foreach my $role (@groupkeys) {
4386: my ($trole,$area,$sec,$extendedarea);
4387: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4388: $trole = $1;
4389: $area = $2;
4390: $sec = $3;
4391: $extendedarea = $area.$sec;
4392: if (exists($$allgroups{$area})) {
4393: foreach my $group (keys(%{$$allgroups{$area}})) {
4394: my $spec = $trole.'.'.$extendedarea;
4395: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4396: $$allgroups{$area}{$group};
1.1064 raeburn 4397: }
1.678 raeburn 4398: }
4399: }
4400: }
4401: }
4402: }
1.800 albertel 4403: foreach my $group (keys(%grouproles)) {
4404: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4405: }
1.800 albertel 4406: foreach my $role (keys(%{$allroles})) {
4407: my %thesepriv;
1.941 raeburn 4408: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4409: foreach my $item (split(/:/,$$allroles{$role})) {
4410: if ($item ne '') {
4411: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4412: if ($restrictions eq '') {
4413: $thesepriv{$privilege}='F';
4414: } elsif ($thesepriv{$privilege} ne 'F') {
4415: $thesepriv{$privilege}.=$restrictions;
4416: }
4417: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4418: }
4419: }
4420: my $thesestr='';
1.1104 raeburn 4421: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4422: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4423: }
4424: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4425: }
4426: return ($author,$adv);
4427: }
4428:
1.994 raeburn 4429: sub role_status {
1.1104 raeburn 4430: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4431: my @pwhere = ();
4432: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4433: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4434: unless (!defined($$role) || $$role eq '') {
4435: $$where=join('.',@pwhere);
4436: $$trolecode=$$role.'.'.$$where;
4437: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4438: $$tstatus='is';
1.1104 raeburn 4439: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4440: $$tstatus='future';
1.1034 raeburn 4441: if ($$tstart<$now) {
4442: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4443: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4444: my (%allroles,%allgroups,$group_privs,
4445: %groups_roles,@rolecodes);
1.1002 raeburn 4446: my %userroles = (
4447: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4448: );
1.1064 raeburn 4449: @rolecodes = ('cm');
1.1002 raeburn 4450: my $spec=$$role.'.'.$$where;
4451: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4452: if ($$role =~ /^cr\//) {
4453: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4454: push(@rolecodes,'cr');
1.1002 raeburn 4455: } elsif ($$role eq 'gr') {
1.1064 raeburn 4456: push(@rolecodes,$$role);
1.1002 raeburn 4457: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4458: $env{'user.name'});
1.1064 raeburn 4459: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4460: (undef,my $group_privs) = split(/\//,$trole);
4461: $group_privs = &unescape($group_privs);
4462: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4463: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 4464: &get_groups_roles($tdomain,$trest,
4465: \%course_roles,\@rolecodes,
4466: \%groups_roles);
1.1002 raeburn 4467: } else {
1.1064 raeburn 4468: push(@rolecodes,$$role);
1.1002 raeburn 4469: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4470: }
1.1064 raeburn 4471: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4472: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4473: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4474: }
4475: }
1.1034 raeburn 4476: $$tstatus = 'is';
1.1002 raeburn 4477: }
1.994 raeburn 4478: }
4479: if ($$tend) {
1.1104 raeburn 4480: if ($$tend<$update) {
1.994 raeburn 4481: $$tstatus='expired';
4482: } elsif ($$tend<$now) {
4483: $$tstatus='will_not';
4484: }
4485: }
4486: }
4487: }
4488: }
4489:
1.1104 raeburn 4490: sub get_groups_roles {
4491: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4492: return unless((ref($cdom_courseroles) eq 'HASH') &&
4493: (ref($rolecodes) eq 'ARRAY') &&
4494: (ref($groups_roles) eq 'HASH'));
4495: if (keys(%{$cdom_courseroles}) > 0) {
4496: my ($cnum) = ($rest =~ /^($match_courseid)/);
4497: if ($cdom ne '' && $cnum ne '') {
4498: foreach my $key (keys(%{$cdom_courseroles})) {
4499: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4500: my $crsrole = $1;
4501: my $crssec = $2;
4502: if ($crsrole =~ /^cr/) {
4503: unless (grep(/^cr$/,@{$rolecodes})) {
4504: push(@{$rolecodes},'cr');
4505: }
4506: } else {
4507: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4508: push(@{$rolecodes},$crsrole);
4509: }
4510: }
4511: my $rolekey = "$crsrole./$cdom/$cnum";
4512: if ($crssec ne '') {
4513: $rolekey .= "/$crssec";
4514: }
4515: $rolekey .= './';
4516: $groups_roles->{$rolekey} = $rolecodes;
4517: }
4518: }
4519: }
4520: }
4521: return;
4522: }
4523:
4524: sub delete_env_groupprivs {
4525: my ($where,$courseroles,$possroles) = @_;
4526: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4527: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4528: unless (ref($courseroles->{$udom}) eq 'HASH') {
4529: %{$courseroles->{$udom}} =
4530: &get_my_roles('','','userroles',['active'],
4531: $possroles,[$udom],1);
4532: }
4533: if (ref($courseroles->{$udom}) eq 'HASH') {
4534: foreach my $item (keys(%{$courseroles->{$udom}})) {
4535: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4536: my $area = '/'.$cdom.'/'.$cnum;
4537: my $privkey = "user.priv.$crsrole.$area";
4538: if ($crssec ne '') {
4539: $privkey .= '/'.$crssec;
4540: }
4541: $privkey .= ".$area/$group";
4542: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4543: }
4544: }
4545: return;
4546: }
4547:
1.994 raeburn 4548: sub check_adhoc_privs {
1.1104 raeburn 4549: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4550: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4551: if ($env{$cckey}) {
4552: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4553: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4554: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4555: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4556: }
4557: } else {
1.1088 raeburn 4558: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4559: }
4560: }
4561:
4562: sub set_adhoc_privileges {
4563: # role can be cc or ca
1.1088 raeburn 4564: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4565: my $area = '/'.$dcdom.'/'.$pickedcourse;
4566: my $spec = $role.'.'.$area;
4567: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4568: $env{'user.name'});
4569: my %ccrole = ();
4570: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4571: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4572: &appenv(\%userroles,[$role,'cm']);
4573: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4574: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4575: &appenv( {'request.role' => $spec,
4576: 'request.role.domain' => $dcdom,
4577: 'request.course.sec' => ''
4578: }
4579: );
4580: my $tadv=0;
4581: if (&allowed('adv') eq 'F') { $tadv=1; }
4582: &appenv({'request.role.adv' => $tadv});
4583: }
1.994 raeburn 4584: }
4585:
1.12 www 4586: # --------------------------------------------------------------- get interface
4587:
4588: sub get {
1.131 albertel 4589: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4590: my $items='';
1.800 albertel 4591: foreach my $item (@$storearr) {
4592: $items.=&escape($item).'&';
1.191 harris41 4593: }
1.12 www 4594: $items=~s/\&$//;
1.620 albertel 4595: if (!$udomain) { $udomain=$env{'user.domain'}; }
4596: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4597: my $uhome=&homeserver($uname,$udomain);
4598:
1.133 albertel 4599: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4600: my @pairs=split(/\&/,$rep);
1.273 albertel 4601: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4602: return @pairs;
4603: }
1.15 www 4604: my %returnhash=();
1.42 www 4605: my $i=0;
1.800 albertel 4606: foreach my $item (@$storearr) {
4607: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4608: $i++;
1.191 harris41 4609: }
1.15 www 4610: return %returnhash;
1.27 www 4611: }
4612:
4613: # --------------------------------------------------------------- del interface
4614:
4615: sub del {
1.133 albertel 4616: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4617: my $items='';
1.800 albertel 4618: foreach my $item (@$storearr) {
4619: $items.=&escape($item).'&';
1.191 harris41 4620: }
1.984 neumanie 4621:
1.27 www 4622: $items=~s/\&$//;
1.620 albertel 4623: if (!$udomain) { $udomain=$env{'user.domain'}; }
4624: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4625: my $uhome=&homeserver($uname,$udomain);
4626: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4627: }
4628:
4629: # -------------------------------------------------------------- dump interface
4630:
4631: sub dump {
1.1086 raeburn 4632: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4633: if (!$udomain) { $udomain=$env{'user.domain'}; }
4634: if (!$uname) { $uname=$env{'user.name'}; }
4635: my $uhome=&homeserver($uname,$udomain);
4636: if ($regexp) {
4637: $regexp=&escape($regexp);
4638: } else {
4639: $regexp='.';
4640: }
1.1086 raeburn 4641: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4642: my @pairs=split(/\&/,$rep);
4643: my %returnhash=();
1.1098 foxr 4644: if (!($rep =~ /^error/ )) {
4645: foreach my $item (@pairs) {
4646: my ($key,$value)=split(/=/,$item,2);
4647: $key = &unescape($key);
4648: next if ($key =~ /^error: 2 /);
4649: $returnhash{$key}=&thaw_unescape($value);
4650: }
1.755 albertel 4651: }
4652: return %returnhash;
1.407 www 4653: }
4654:
1.1098 foxr 4655:
1.717 albertel 4656: # --------------------------------------------------------- dumpstore interface
4657:
4658: sub dumpstore {
4659: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4660: if (!$udomain) { $udomain=$env{'user.domain'}; }
4661: if (!$uname) { $uname=$env{'user.name'}; }
4662: my $uhome=&homeserver($uname,$udomain);
4663: if ($regexp) {
4664: $regexp=&escape($regexp);
4665: } else {
4666: $regexp='.';
4667: }
4668: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4669: my @pairs=split(/\&/,$rep);
4670: my %returnhash=();
4671: foreach my $item (@pairs) {
4672: my ($key,$value)=split(/=/,$item,2);
4673: next if ($key =~ /^error: 2 /);
4674: $returnhash{$key}=&thaw_unescape($value);
4675: }
4676: return %returnhash;
1.717 albertel 4677: }
4678:
1.407 www 4679: # -------------------------------------------------------------- keys interface
4680:
4681: sub getkeys {
4682: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4683: if (!$udomain) { $udomain=$env{'user.domain'}; }
4684: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4685: my $uhome=&homeserver($uname,$udomain);
4686: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4687: my @keyarray=();
1.800 albertel 4688: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4689: next if ($key =~ /^error: 2 /);
1.800 albertel 4690: push(@keyarray,&unescape($key));
1.407 www 4691: }
4692: return @keyarray;
1.318 matthew 4693: }
4694:
1.319 matthew 4695: # --------------------------------------------------------------- currentdump
4696: sub currentdump {
1.328 matthew 4697: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4698: $courseid = $env{'request.course.id'} if (! defined($courseid));
4699: $sdom = $env{'user.domain'} if (! defined($sdom));
4700: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4701: my $uhome = &homeserver($sname,$sdom);
4702: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4703: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4704: #
1.318 matthew 4705: my %returnhash=();
1.319 matthew 4706: #
4707: if ($rep eq "unknown_cmd") {
4708: # an old lond will not know currentdump
4709: # Do a dump and make it look like a currentdump
1.822 albertel 4710: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4711: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4712: my %hash = @tmp;
4713: @tmp=();
1.424 matthew 4714: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4715: } else {
4716: my @pairs=split(/\&/,$rep);
1.800 albertel 4717: foreach my $pair (@pairs) {
4718: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4719: my ($symb,$param) = split(/:/,$key);
4720: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4721: &thaw_unescape($value);
1.319 matthew 4722: }
1.191 harris41 4723: }
1.12 www 4724: return %returnhash;
1.424 matthew 4725: }
4726:
4727: sub convert_dump_to_currentdump{
4728: my %hash = %{shift()};
4729: my %returnhash;
4730: # Code ripped from lond, essentially. The only difference
4731: # here is the unescaping done by lonnet::dump(). Conceivably
4732: # we might run in to problems with parameter names =~ /^v\./
4733: while (my ($key,$value) = each(%hash)) {
4734: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4735: $symb = &unescape($symb);
4736: $param = &unescape($param);
1.424 matthew 4737: next if ($v eq 'version' || $symb eq 'keys');
4738: next if (exists($returnhash{$symb}) &&
4739: exists($returnhash{$symb}->{$param}) &&
4740: $returnhash{$symb}->{'v.'.$param} > $v);
4741: $returnhash{$symb}->{$param}=$value;
4742: $returnhash{$symb}->{'v.'.$param}=$v;
4743: }
4744: #
4745: # Remove all of the keys in the hashes which keep track of
4746: # the version of the parameter.
4747: while (my ($symb,$param_hash) = each(%returnhash)) {
4748: # use a foreach because we are going to delete from the hash.
4749: foreach my $key (keys(%$param_hash)) {
4750: delete($param_hash->{$key}) if ($key =~ /^v\./);
4751: }
4752: }
4753: return \%returnhash;
1.12 www 4754: }
4755:
1.627 albertel 4756: # ------------------------------------------------------ critical inc interface
4757:
4758: sub cinc {
4759: return &inc(@_,'critical');
4760: }
4761:
1.449 matthew 4762: # --------------------------------------------------------------- inc interface
4763:
4764: sub inc {
1.627 albertel 4765: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4766: if (!$udomain) { $udomain=$env{'user.domain'}; }
4767: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4768: my $uhome=&homeserver($uname,$udomain);
4769: my $items='';
4770: if (! ref($store)) {
4771: # got a single value, so use that instead
4772: $items = &escape($store).'=&';
4773: } elsif (ref($store) eq 'SCALAR') {
4774: $items = &escape($$store).'=&';
4775: } elsif (ref($store) eq 'ARRAY') {
4776: $items = join('=&',map {&escape($_);} @{$store});
4777: } elsif (ref($store) eq 'HASH') {
4778: while (my($key,$value) = each(%{$store})) {
4779: $items.= &escape($key).'='.&escape($value).'&';
4780: }
4781: }
4782: $items=~s/\&$//;
1.627 albertel 4783: if ($critical) {
4784: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4785: } else {
4786: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4787: }
1.449 matthew 4788: }
4789:
1.12 www 4790: # --------------------------------------------------------------- put interface
4791:
4792: sub put {
1.134 albertel 4793: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4794: if (!$udomain) { $udomain=$env{'user.domain'}; }
4795: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4796: my $uhome=&homeserver($uname,$udomain);
1.12 www 4797: my $items='';
1.800 albertel 4798: foreach my $item (keys(%$storehash)) {
4799: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4800: }
1.12 www 4801: $items=~s/\&$//;
1.134 albertel 4802: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4803: }
4804:
1.631 albertel 4805: # ------------------------------------------------------------ newput interface
4806:
4807: sub newput {
4808: my ($namespace,$storehash,$udomain,$uname)=@_;
4809: if (!$udomain) { $udomain=$env{'user.domain'}; }
4810: if (!$uname) { $uname=$env{'user.name'}; }
4811: my $uhome=&homeserver($uname,$udomain);
4812: my $items='';
4813: foreach my $key (keys(%$storehash)) {
4814: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4815: }
4816: $items=~s/\&$//;
4817: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4818: }
4819:
4820: # --------------------------------------------------------- putstore interface
4821:
1.524 raeburn 4822: sub putstore {
1.715 albertel 4823: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4824: if (!$udomain) { $udomain=$env{'user.domain'}; }
4825: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4826: my $uhome=&homeserver($uname,$udomain);
4827: my $items='';
1.715 albertel 4828: foreach my $key (keys(%$storehash)) {
4829: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4830: }
1.715 albertel 4831: $items=~s/\&$//;
1.716 albertel 4832: my $esc_symb=&escape($symb);
4833: my $esc_v=&escape($version);
1.715 albertel 4834: my $reply =
1.716 albertel 4835: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4836: $uhome);
4837: if ($reply eq 'unknown_cmd') {
1.716 albertel 4838: # gfall back to way things use to be done
1.715 albertel 4839: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4840: $uname);
1.524 raeburn 4841: }
1.715 albertel 4842: return $reply;
4843: }
4844:
4845: sub old_putstore {
1.716 albertel 4846: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4847: if (!$udomain) { $udomain=$env{'user.domain'}; }
4848: if (!$uname) { $uname=$env{'user.name'}; }
4849: my $uhome=&homeserver($uname,$udomain);
4850: my %newstorehash;
1.800 albertel 4851: foreach my $item (keys(%$storehash)) {
4852: my $key = $version.':'.&escape($symb).':'.$item;
4853: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4854: }
4855: my $items='';
4856: my %allitems = ();
1.800 albertel 4857: foreach my $item (keys(%newstorehash)) {
4858: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4859: my $key = $1.':keys:'.$2;
4860: $allitems{$key} .= $3.':';
4861: }
1.800 albertel 4862: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4863: }
1.800 albertel 4864: foreach my $item (keys(%allitems)) {
4865: $allitems{$item} =~ s/\:$//;
4866: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4867: }
4868: $items=~s/\&$//;
4869: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4870: }
4871:
1.47 www 4872: # ------------------------------------------------------ critical put interface
4873:
4874: sub cput {
1.134 albertel 4875: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4876: if (!$udomain) { $udomain=$env{'user.domain'}; }
4877: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4878: my $uhome=&homeserver($uname,$udomain);
1.47 www 4879: my $items='';
1.800 albertel 4880: foreach my $item (keys(%$storehash)) {
4881: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4882: }
1.47 www 4883: $items=~s/\&$//;
1.134 albertel 4884: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4885: }
4886:
4887: # -------------------------------------------------------------- eget interface
4888:
4889: sub eget {
1.133 albertel 4890: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4891: my $items='';
1.800 albertel 4892: foreach my $item (@$storearr) {
4893: $items.=&escape($item).'&';
1.191 harris41 4894: }
1.12 www 4895: $items=~s/\&$//;
1.620 albertel 4896: if (!$udomain) { $udomain=$env{'user.domain'}; }
4897: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4898: my $uhome=&homeserver($uname,$udomain);
4899: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4900: my @pairs=split(/\&/,$rep);
4901: my %returnhash=();
1.42 www 4902: my $i=0;
1.800 albertel 4903: foreach my $item (@$storearr) {
4904: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4905: $i++;
1.191 harris41 4906: }
1.12 www 4907: return %returnhash;
4908: }
4909:
1.667 albertel 4910: # ------------------------------------------------------------ tmpput interface
4911: sub tmpput {
1.802 raeburn 4912: my ($storehash,$server,$context)=@_;
1.667 albertel 4913: my $items='';
1.800 albertel 4914: foreach my $item (keys(%$storehash)) {
4915: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4916: }
4917: $items=~s/\&$//;
1.802 raeburn 4918: if (defined($context)) {
4919: $items .= ':'.&escape($context);
4920: }
1.667 albertel 4921: return &reply("tmpput:$items",$server);
4922: }
4923:
4924: # ------------------------------------------------------------ tmpget interface
4925: sub tmpget {
1.688 albertel 4926: my ($token,$server)=@_;
4927: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4928: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4929: my %returnhash;
4930: foreach my $item (split(/\&/,$rep)) {
4931: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4932: next if ($key =~ /^error: 2 /);
1.667 albertel 4933: $returnhash{&unescape($key)}=&thaw_unescape($value);
4934: }
4935: return %returnhash;
4936: }
4937:
1.1113 raeburn 4938: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 4939: sub tmpdel {
4940: my ($token,$server)=@_;
4941: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4942: return &reply("tmpdel:$token",$server);
4943: }
4944:
1.765 albertel 4945: # -------------------------------------------------- portfolio access checking
4946:
4947: sub portfolio_access {
1.766 albertel 4948: my ($requrl) = @_;
1.765 albertel 4949: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4950: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4951: if ($result) {
4952: my %setters;
4953: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4954: my ($startblock,$endblock) =
4955: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4956: if ($startblock && $endblock) {
4957: return 'B';
4958: }
4959: } else {
4960: my ($startblock,$endblock) =
4961: &Apache::loncommon::blockcheck(\%setters,'port');
4962: if ($startblock && $endblock) {
4963: return 'B';
4964: }
4965: }
4966: }
1.765 albertel 4967: if ($result eq 'ok') {
1.766 albertel 4968: return 'F';
1.765 albertel 4969: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4970: return 'A';
1.765 albertel 4971: }
1.766 albertel 4972: return '';
1.765 albertel 4973: }
4974:
4975: sub get_portfolio_access {
1.767 albertel 4976: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4977:
4978: if (!ref($access_hash)) {
4979: my $current_perms = &get_portfile_permissions($udom,$unum);
4980: my %access_controls = &get_access_controls($current_perms,$group,
4981: $file_name);
4982: $access_hash = $access_controls{$file_name};
4983: }
4984:
1.765 albertel 4985: my ($public,$guest,@domains,@users,@courses,@groups);
4986: my $now = time;
4987: if (ref($access_hash) eq 'HASH') {
4988: foreach my $key (keys(%{$access_hash})) {
4989: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4990: if ($start > $now) {
4991: next;
4992: }
4993: if ($end && $end<$now) {
4994: next;
4995: }
4996: if ($scope eq 'public') {
4997: $public = $key;
4998: last;
4999: } elsif ($scope eq 'guest') {
5000: $guest = $key;
5001: } elsif ($scope eq 'domains') {
5002: push(@domains,$key);
5003: } elsif ($scope eq 'users') {
5004: push(@users,$key);
5005: } elsif ($scope eq 'course') {
5006: push(@courses,$key);
5007: } elsif ($scope eq 'group') {
5008: push(@groups,$key);
5009: }
5010: }
5011: if ($public) {
5012: return 'ok';
5013: }
5014: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5015: if ($guest) {
5016: return $guest;
5017: }
5018: } else {
5019: if (@domains > 0) {
5020: foreach my $domkey (@domains) {
5021: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5022: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5023: return 'ok';
5024: }
5025: }
5026: }
5027: }
5028: if (@users > 0) {
5029: foreach my $userkey (@users) {
1.865 raeburn 5030: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5031: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5032: if (ref($item) eq 'HASH') {
5033: if (($item->{'uname'} eq $env{'user.name'}) &&
5034: ($item->{'udom'} eq $env{'user.domain'})) {
5035: return 'ok';
5036: }
5037: }
5038: }
5039: }
1.765 albertel 5040: }
5041: }
5042: my %roleshash;
5043: my @courses_and_groups = @courses;
5044: push(@courses_and_groups,@groups);
5045: if (@courses_and_groups > 0) {
5046: my (%allgroups,%allroles);
5047: my ($start,$end,$role,$sec,$group);
5048: foreach my $envkey (%env) {
1.1060 raeburn 5049: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5050: my $cid = $2.'_'.$3;
5051: if ($1 eq 'gr') {
5052: $group = $4;
5053: $allgroups{$cid}{$group} = $env{$envkey};
5054: } else {
5055: if ($4 eq '') {
5056: $sec = 'none';
5057: } else {
5058: $sec = $4;
5059: }
5060: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5061: }
1.811 albertel 5062: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5063: my $cid = $2.'_'.$3;
5064: if ($4 eq '') {
5065: $sec = 'none';
5066: } else {
5067: $sec = $4;
5068: }
5069: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5070: }
5071: }
5072: if (keys(%allroles) == 0) {
5073: return;
5074: }
5075: foreach my $key (@courses_and_groups) {
5076: my %content = %{$$access_hash{$key}};
5077: my $cnum = $content{'number'};
5078: my $cdom = $content{'domain'};
5079: my $cid = $cdom.'_'.$cnum;
5080: if (!exists($allroles{$cid})) {
5081: next;
5082: }
5083: foreach my $role_id (keys(%{$content{'roles'}})) {
5084: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5085: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5086: my @status = @{$content{'roles'}{$role_id}{'access'}};
5087: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5088: foreach my $role (keys(%{$allroles{$cid}})) {
5089: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5090: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5091: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5092: if (grep/^all$/,@sections) {
5093: return 'ok';
5094: } else {
5095: if (grep/^$sec$/,@sections) {
5096: return 'ok';
5097: }
5098: }
5099: }
5100: }
5101: if (keys(%{$allgroups{$cid}}) == 0) {
5102: if (grep/^none$/,@groups) {
5103: return 'ok';
5104: }
5105: } else {
5106: if (grep/^all$/,@groups) {
5107: return 'ok';
5108: }
5109: foreach my $group (keys(%{$allgroups{$cid}})) {
5110: if (grep/^$group$/,@groups) {
5111: return 'ok';
5112: }
5113: }
5114: }
5115: }
5116: }
5117: }
5118: }
5119: }
5120: if ($guest) {
5121: return $guest;
5122: }
5123: }
5124: }
5125: return;
5126: }
5127:
5128: sub course_group_datechecker {
5129: my ($dates,$now,$status) = @_;
5130: my ($start,$end) = split(/\./,$dates);
5131: if (!$start && !$end) {
5132: return 'ok';
5133: }
5134: if (grep/^active$/,@{$status}) {
5135: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5136: return 'ok';
5137: }
5138: }
5139: if (grep/^previous$/,@{$status}) {
5140: if ($end > $now ) {
5141: return 'ok';
5142: }
5143: }
5144: if (grep/^future$/,@{$status}) {
5145: if ($start > $now) {
5146: return 'ok';
5147: }
5148: }
5149: return;
5150: }
5151:
5152: sub parse_portfolio_url {
5153: my ($url) = @_;
5154:
5155: my ($type,$udom,$unum,$group,$file_name);
5156:
1.823 albertel 5157: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5158: $type = 1;
5159: $udom = $1;
5160: $unum = $2;
5161: $file_name = $3;
1.823 albertel 5162: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5163: $type = 2;
5164: $udom = $1;
5165: $unum = $2;
5166: $group = $3;
5167: $file_name = $3.'/'.$4;
5168: }
5169: if (wantarray) {
5170: return ($type,$udom,$unum,$file_name,$group);
5171: }
5172: return $type;
5173: }
5174:
5175: sub is_portfolio_url {
5176: my ($url) = @_;
5177: return scalar(&parse_portfolio_url($url));
5178: }
5179:
1.798 raeburn 5180: sub is_portfolio_file {
5181: my ($file) = @_;
1.820 raeburn 5182: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5183: return 1;
5184: }
5185: return;
5186: }
5187:
1.976 raeburn 5188: sub usertools_access {
1.1084 raeburn 5189: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5190: my ($access,%tools);
5191: if ($context eq '') {
5192: $context = 'tools';
5193: }
5194: if ($context eq 'requestcourses') {
5195: %tools = (
5196: official => 1,
5197: unofficial => 1,
1.1006 raeburn 5198: community => 1,
1.985 raeburn 5199: );
5200: } else {
5201: %tools = (
5202: aboutme => 1,
5203: blog => 1,
5204: portfolio => 1,
5205: );
5206: }
1.976 raeburn 5207: return if (!defined($tools{$tool}));
5208:
5209: if ((!defined($udom)) || (!defined($uname))) {
5210: $udom = $env{'user.domain'};
5211: $uname = $env{'user.name'};
5212: }
5213:
1.978 raeburn 5214: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5215: if ($action ne 'reload') {
1.985 raeburn 5216: if ($context eq 'requestcourses') {
5217: return $env{'environment.canrequest.'.$tool};
5218: } else {
5219: return $env{'environment.availabletools.'.$tool};
5220: }
5221: }
1.976 raeburn 5222: }
5223:
5224: my ($toolstatus,$inststatus);
5225:
1.985 raeburn 5226: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5227: ($action ne 'reload')) {
5228: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5229: $inststatus = $env{'environment.inststatus'};
5230: } else {
1.1084 raeburn 5231: if (ref($userenvref) eq 'HASH') {
5232: $toolstatus = $userenvref->{$context.'.'.$tool};
5233: $inststatus = $userenvref->{'inststatus'};
5234: } else {
5235: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5236: $toolstatus = $userenv{$context.'.'.$tool};
5237: $inststatus = $userenv{'inststatus'};
5238: }
1.976 raeburn 5239: }
5240:
5241: if ($toolstatus ne '') {
5242: if ($toolstatus) {
5243: $access = 1;
5244: } else {
5245: $access = 0;
5246: }
5247: return $access;
5248: }
5249:
1.1084 raeburn 5250: my ($is_adv,%domdef);
5251: if (ref($is_advref) eq 'HASH') {
5252: $is_adv = $is_advref->{'is_adv'};
5253: } else {
5254: $is_adv = &is_advanced_user($udom,$uname);
5255: }
5256: if (ref($domdefref) eq 'HASH') {
5257: %domdef = %{$domdefref};
5258: } else {
5259: %domdef = &get_domain_defaults($udom);
5260: }
1.976 raeburn 5261: if (ref($domdef{$tool}) eq 'HASH') {
5262: if ($is_adv) {
5263: if ($domdef{$tool}{'_LC_adv'} ne '') {
5264: if ($domdef{$tool}{'_LC_adv'}) {
5265: $access = 1;
5266: } else {
5267: $access = 0;
5268: }
5269: return $access;
5270: }
5271: }
5272: if ($inststatus ne '') {
5273: my ($hasaccess,$hasnoaccess);
5274: foreach my $affiliation (split(/:/,$inststatus)) {
5275: if ($domdef{$tool}{$affiliation} ne '') {
5276: if ($domdef{$tool}{$affiliation}) {
5277: $hasaccess = 1;
5278: } else {
5279: $hasnoaccess = 1;
5280: }
5281: }
5282: }
5283: if ($hasaccess || $hasnoaccess) {
5284: if ($hasaccess) {
5285: $access = 1;
5286: } elsif ($hasnoaccess) {
5287: $access = 0;
5288: }
5289: return $access;
5290: }
5291: } else {
5292: if ($domdef{$tool}{'default'} ne '') {
5293: if ($domdef{$tool}{'default'}) {
5294: $access = 1;
5295: } elsif ($domdef{$tool}{'default'} == 0) {
5296: $access = 0;
5297: }
5298: return $access;
5299: }
5300: }
5301: } else {
1.985 raeburn 5302: if ($context eq 'tools') {
5303: $access = 1;
5304: } else {
5305: $access = 0;
5306: }
1.976 raeburn 5307: return $access;
5308: }
5309: }
5310:
1.1050 raeburn 5311: sub is_course_owner {
5312: my ($cdom,$cnum,$udom,$uname) = @_;
5313: if (($udom eq '') || ($uname eq '')) {
5314: $udom = $env{'user.domain'};
5315: $uname = $env{'user.name'};
5316: }
5317: unless (($udom eq '') || ($uname eq '')) {
5318: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5319: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5320: return 1;
5321: } else {
5322: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5323: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5324: return 1;
5325: }
5326: }
5327: }
5328: }
5329: return;
5330: }
5331:
1.976 raeburn 5332: sub is_advanced_user {
5333: my ($udom,$uname) = @_;
1.1085 raeburn 5334: if ($udom ne '' && $uname ne '') {
5335: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5336: return $env{'user.adv'};
5337: }
5338: }
1.976 raeburn 5339: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5340: my %allroles;
5341: my $is_adv;
5342: foreach my $role (keys(%roleshash)) {
5343: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5344: my $area = '/'.$tdomain.'/'.$trest;
5345: if ($sec ne '') {
5346: $area .= '/'.$sec;
5347: }
5348: if (($area ne '') && ($trole ne '')) {
5349: my $spec=$trole.'.'.$area;
5350: if ($trole =~ /^cr\//) {
5351: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5352: } elsif ($trole ne 'gr') {
5353: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5354: }
5355: }
5356: }
5357: foreach my $role (keys(%allroles)) {
5358: last if ($is_adv);
5359: foreach my $item (split(/:/,$allroles{$role})) {
5360: if ($item ne '') {
5361: my ($privilege,$restrictions)=split(/&/,$item);
5362: if ($privilege eq 'adv') {
5363: $is_adv = 1;
5364: last;
5365: }
5366: }
5367: }
5368: }
5369: return $is_adv;
5370: }
1.798 raeburn 5371:
1.1035 raeburn 5372: sub check_can_request {
1.1036 raeburn 5373: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5374: my $canreq = 0;
5375: my ($types,$typename) = &Apache::loncommon::course_types();
5376: my @options = ('approval','validate','autolimit');
5377: my $optregex = join('|',@options);
5378: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5379: foreach my $type (@{$types}) {
5380: if (&usertools_access($env{'user.name'},
5381: $env{'user.domain'},
5382: $type,undef,'requestcourses')) {
5383: $canreq ++;
1.1036 raeburn 5384: if (ref($request_domains) eq 'HASH') {
5385: push(@{$request_domains->{$type}},$env{'user.domain'});
5386: }
1.1035 raeburn 5387: if ($dom eq $env{'user.domain'}) {
5388: $can_request->{$type} = 1;
5389: }
5390: }
5391: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5392: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5393: if (@curr > 0) {
1.1036 raeburn 5394: foreach my $item (@curr) {
5395: if (ref($request_domains) eq 'HASH') {
5396: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5397: if ($otherdom ne '') {
5398: if (ref($request_domains->{$type}) eq 'ARRAY') {
5399: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5400: push(@{$request_domains->{$type}},$otherdom);
5401: }
5402: } else {
5403: push(@{$request_domains->{$type}},$otherdom);
5404: }
5405: }
5406: }
5407: }
5408: unless($dom eq $env{'user.domain'}) {
5409: $canreq ++;
1.1035 raeburn 5410: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5411: $can_request->{$type} = 1;
5412: }
5413: }
5414: }
5415: }
5416: }
5417: }
5418: return $canreq;
5419: }
5420:
1.341 www 5421: # ---------------------------------------------- Custom access rule evaluation
5422:
5423: sub customaccess {
5424: my ($priv,$uri)=@_;
1.807 albertel 5425: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5426: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5427: $udom = &LONCAPA::clean_domain($udom);
5428: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5429: my $access=0;
1.800 albertel 5430: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5431: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5432: if ($type eq 'user') {
5433: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5434: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5435: if ($tdom) {
5436: if ($tdom ne $env{'user.domain'}) { next; }
5437: }
1.896 albertel 5438: if ($tuname) {
5439: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5440: }
5441: $access=($effect eq 'allow');
5442: last;
5443: }
5444: } else {
5445: if ($role) {
5446: if ($role ne $urole) { next; }
5447: }
5448: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5449: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5450: if ($tdom) {
5451: if ($tdom ne $udom) { next; }
5452: }
5453: if ($tcrs) {
5454: if ($tcrs ne $ucrs) { next; }
5455: }
5456: if ($tsec) {
5457: if ($tsec ne $usec) { next; }
5458: }
5459: $access=($effect eq 'allow');
5460: last;
5461: }
5462: if ($realm eq '' && $role eq '') {
5463: $access=($effect eq 'allow');
5464: }
1.402 bowersj2 5465: }
1.341 www 5466: }
5467: return $access;
5468: }
5469:
1.103 harris41 5470: # ------------------------------------------------- Check for a user privilege
1.12 www 5471:
5472: sub allowed {
1.810 raeburn 5473: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5474: my $ver_orguri=$uri;
1.439 www 5475: $uri=&deversion($uri);
1.152 www 5476: my $orguri=$uri;
1.52 www 5477: $uri=&declutter($uri);
1.809 raeburn 5478:
1.810 raeburn 5479: if ($priv eq 'evb') {
5480: # Evade communication block restrictions for specified role in a course
5481: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5482: return $1;
5483: } else {
5484: return;
5485: }
5486: }
5487:
1.620 albertel 5488: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5489: # Free bre access to adm and meta resources
1.775 albertel 5490: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5491: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5492: && ($priv eq 'bre')) {
1.14 www 5493: return 'F';
1.159 www 5494: }
5495:
1.545 banghart 5496: # Free bre access to user's own portfolio contents
1.714 raeburn 5497: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5498: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5499: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5500: my %setters;
5501: my ($startblock,$endblock) =
5502: &Apache::loncommon::blockcheck(\%setters,'port');
5503: if ($startblock && $endblock) {
5504: return 'B';
5505: } else {
5506: return 'F';
5507: }
1.545 banghart 5508: }
5509:
1.762 raeburn 5510: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5511: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5512: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5513: if (exists($env{'request.course.id'})) {
5514: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5515: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5516: if (($domain eq $cdom) && ($name eq $cnum)) {
5517: my $courseprivid=$env{'request.course.id'};
5518: $courseprivid=~s/\_/\//;
5519: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5520: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5521: return $1;
1.762 raeburn 5522: } else {
5523: if ($env{'request.course.sec'}) {
5524: $courseprivid.='/'.$env{'request.course.sec'};
5525: }
5526: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5527: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5528: return $2;
5529: }
1.714 raeburn 5530: }
5531: }
5532: }
5533: }
5534:
1.159 www 5535: # Free bre to public access
5536:
5537: if ($priv eq 'bre') {
1.238 www 5538: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5539: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5540: return 'F';
5541: }
1.238 www 5542: if ($copyright eq 'priv') {
5543: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5544: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5545: return '';
5546: }
5547: }
5548: if ($copyright eq 'domain') {
5549: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5550: unless (($env{'user.domain'} eq $1) ||
5551: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5552: return '';
5553: }
1.262 matthew 5554: }
1.620 albertel 5555: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5556: # Library role, so allow browsing of resources in this domain.
5557: return 'F';
1.238 www 5558: }
1.341 www 5559: if ($copyright eq 'custom') {
5560: unless (&customaccess($priv,$uri)) { return ''; }
5561: }
1.14 www 5562: }
1.264 matthew 5563: # Domain coordinator is trying to create a course
1.620 albertel 5564: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5565: # uri is the requested domain in this case.
5566: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5567: # a role of dc for the domain in question.
1.620 albertel 5568: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5569: }
1.29 www 5570:
1.52 www 5571: my $thisallowed='';
5572: my $statecond=0;
5573: my $courseprivid='';
5574:
1.1039 raeburn 5575: my $ownaccess;
1.1043 raeburn 5576: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5577: if (($priv eq 'bro') && ($env{'user.author'})) {
5578: if ($uri eq '') {
5579: $ownaccess = 1;
5580: } else {
5581: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5582: my $udom = $env{'user.domain'};
5583: my $uname = $env{'user.name'};
5584: if ($uri =~ m{^\Q$udom\E/?$}) {
5585: $ownaccess = 1;
1.1040 raeburn 5586: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5587: unless ($uri =~ m{\.\./}) {
5588: $ownaccess = 1;
5589: }
5590: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5591: my $now = time;
5592: if ($uri =~ m{^([^/]+)/?$}) {
5593: my $adom = $1;
5594: foreach my $key (keys(%env)) {
1.1042 raeburn 5595: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5596: my ($start,$end) = split('.',$env{$key});
5597: if (($now >= $start) && (!$end || $end < $now)) {
5598: $ownaccess = 1;
5599: last;
5600: }
5601: }
5602: }
5603: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5604: my $adom = $1;
5605: my $aname = $2;
1.1042 raeburn 5606: foreach my $role ('ca','aa') {
5607: if ($env{"user.role.$role./$adom/$aname"}) {
5608: my ($start,$end) =
5609: split('.',$env{"user.role.$role./$adom/$aname"});
5610: if (($now >= $start) && (!$end || $end < $now)) {
5611: $ownaccess = 1;
5612: last;
5613: }
1.1039 raeburn 5614: }
5615: }
5616: }
5617: }
5618: }
5619: }
5620: }
5621:
1.52 www 5622: # Course
5623:
1.620 albertel 5624: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5625: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5626: $thisallowed.=$1;
5627: }
1.52 www 5628: }
1.29 www 5629:
1.52 www 5630: # Domain
5631:
1.620 albertel 5632: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5633: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5634: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5635: $thisallowed.=$1;
5636: }
1.12 www 5637: }
1.52 www 5638:
5639: # Course: uri itself is a course
1.66 www 5640: my $courseuri=$uri;
5641: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5642: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5643:
1.620 albertel 5644: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5645: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5646: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5647: $thisallowed.=$1;
5648: }
1.12 www 5649: }
1.29 www 5650:
1.665 albertel 5651: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5652: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5653: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5654: $thisallowed='';
1.671 raeburn 5655: my ($match)=&is_on_map($uri);
5656: if ($match) {
5657: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5658: =~/\Q$priv\E\&([^\:]*)/) {
5659: $thisallowed.=$1;
5660: }
5661: } else {
1.705 albertel 5662: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5663: if ($refuri) {
5664: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5665: $thisallowed='F';
1.671 raeburn 5666: } else {
5667: $refuri=&declutter($refuri);
5668: my ($match) = &is_on_map($refuri);
5669: if ($match) {
5670: $thisallowed='F';
5671: }
1.669 raeburn 5672: }
1.671 raeburn 5673: }
5674: }
1.314 www 5675: }
1.492 albertel 5676:
1.766 albertel 5677: if ($priv eq 'bre'
5678: && $thisallowed ne 'F'
5679: && $thisallowed ne '2'
5680: && &is_portfolio_url($uri)) {
5681: $thisallowed = &portfolio_access($uri);
5682: }
5683:
1.52 www 5684: # Full access at system, domain or course-wide level? Exit.
1.29 www 5685: if ($thisallowed=~/F/) {
5686: return 'F';
5687: }
5688:
1.52 www 5689: # If this is generating or modifying users, exit with special codes
1.29 www 5690:
1.643 www 5691: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5692: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5693: my ($audom,$auname)=split('/',$uri);
1.643 www 5694: # no author name given, so this just checks on the general right to make a co-author in this domain
5695: unless ($auname) { return $thisallowed; }
5696: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5697: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5698: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5699: ($audom ne $env{'request.role.domain'}))) { return ''; }
5700: }
1.52 www 5701: return $thisallowed;
5702: }
5703: #
1.103 harris41 5704: # Gathered so far: system, domain and course wide privileges
1.52 www 5705: #
5706: # Course: See if uri or referer is an individual resource that is part of
5707: # the course
5708:
1.620 albertel 5709: if ($env{'request.course.id'}) {
1.232 www 5710:
1.620 albertel 5711: $courseprivid=$env{'request.course.id'};
5712: if ($env{'request.course.sec'}) {
5713: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5714: }
5715: $courseprivid=~s/\_/\//;
5716: my $checkreferer=1;
1.232 www 5717: my ($match,$cond)=&is_on_map($uri);
5718: if ($match) {
5719: $statecond=$cond;
1.620 albertel 5720: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5721: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5722: $thisallowed.=$1;
5723: $checkreferer=0;
5724: }
1.29 www 5725: }
1.83 www 5726:
1.148 www 5727: if ($checkreferer) {
1.620 albertel 5728: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5729: unless ($refuri) {
1.800 albertel 5730: foreach my $key (keys(%env)) {
5731: if ($key=~/^httpref\..*\*/) {
5732: my $pattern=$key;
1.156 www 5733: $pattern=~s/^httpref\.\/res\///;
1.148 www 5734: $pattern=~s/\*/\[\^\/\]\+/g;
5735: $pattern=~s/\//\\\//g;
1.152 www 5736: if ($orguri=~/$pattern/) {
1.800 albertel 5737: $refuri=$env{$key};
1.148 www 5738: }
5739: }
1.191 harris41 5740: }
1.148 www 5741: }
1.232 www 5742:
1.148 www 5743: if ($refuri) {
1.152 www 5744: $refuri=&declutter($refuri);
1.232 www 5745: my ($match,$cond)=&is_on_map($refuri);
5746: if ($match) {
5747: my $refstatecond=$cond;
1.620 albertel 5748: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5749: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5750: $thisallowed.=$1;
1.53 www 5751: $uri=$refuri;
5752: $statecond=$refstatecond;
1.52 www 5753: }
5754: }
1.148 www 5755: }
1.29 www 5756: }
1.52 www 5757: }
1.29 www 5758:
1.52 www 5759: #
1.103 harris41 5760: # Gathered now: all privileges that could apply, and condition number
1.52 www 5761: #
5762: #
5763: # Full or no access?
5764: #
1.29 www 5765:
1.52 www 5766: if ($thisallowed=~/F/) {
5767: return 'F';
5768: }
1.29 www 5769:
1.52 www 5770: unless ($thisallowed) {
5771: return '';
5772: }
1.29 www 5773:
1.52 www 5774: # Restrictions exist, deal with them
5775: #
5776: # C:according to course preferences
5777: # R:according to resource settings
5778: # L:unless locked
5779: # X:according to user session state
5780: #
5781:
5782: # Possibly locked functionality, check all courses
1.54 www 5783: # Locks might take effect only after 10 minutes cache expiration for other
5784: # courses, and 2 minutes for current course
1.52 www 5785:
5786: my $envkey;
5787: if ($thisallowed=~/L/) {
1.1000 raeburn 5788: foreach $envkey (keys(%env)) {
1.54 www 5789: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5790: my $courseid=$2;
5791: my $roleid=$1.'.'.$2;
1.92 www 5792: $courseid=~s/^\///;
1.54 www 5793: my $expiretime=600;
1.620 albertel 5794: if ($env{'request.role'} eq $roleid) {
1.54 www 5795: $expiretime=120;
5796: }
5797: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5798: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5799: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5800: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5801: }
1.620 albertel 5802: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5803: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5804: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5805: &log($env{'user.domain'},$env{'user.name'},
5806: $env{'user.home'},
1.57 www 5807: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5808: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5809: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5810: return '';
5811: }
5812: }
1.620 albertel 5813: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5814: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5815: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5816: &log($env{'user.domain'},$env{'user.name'},
5817: $env{'user.home'},
1.57 www 5818: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5819: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5820: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5821: return '';
5822: }
5823: }
5824: }
1.29 www 5825: }
1.52 www 5826: }
5827:
5828: #
5829: # Rest of the restrictions depend on selected course
5830: #
5831:
1.620 albertel 5832: unless ($env{'request.course.id'}) {
1.766 albertel 5833: if ($thisallowed eq 'A') {
5834: return 'A';
1.814 raeburn 5835: } elsif ($thisallowed eq 'B') {
5836: return 'B';
1.766 albertel 5837: } else {
5838: return '1';
5839: }
1.52 www 5840: }
1.29 www 5841:
1.52 www 5842: #
5843: # Now user is definitely in a course
5844: #
1.53 www 5845:
5846:
5847: # Course preferences
5848:
5849: if ($thisallowed=~/C/) {
1.620 albertel 5850: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5851: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5852: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5853: =~/\Q$rolecode\E/) {
1.1103 raeburn 5854: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5855: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5856: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5857: $env{'request.course.id'});
5858: }
1.237 www 5859: return '';
5860: }
5861:
1.620 albertel 5862: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5863: =~/\Q$unamedom\E/) {
1.1103 raeburn 5864: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5865: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5866: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5867: $env{'request.course.id'});
5868: }
1.54 www 5869: return '';
5870: }
1.53 www 5871: }
5872:
5873: # Resource preferences
5874:
5875: if ($thisallowed=~/R/) {
1.620 albertel 5876: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5877: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 5878: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5879: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5880: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5881: }
5882: return '';
1.54 www 5883: }
1.53 www 5884: }
1.30 www 5885:
1.246 www 5886: # Restricted by state or randomout?
1.30 www 5887:
1.52 www 5888: if ($thisallowed=~/X/) {
1.620 albertel 5889: if ($env{'acc.randomout'}) {
1.579 albertel 5890: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5891: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5892: return '';
5893: }
1.247 www 5894: }
5895: if (&condval($statecond)) {
1.52 www 5896: return '2';
5897: } else {
5898: return '';
5899: }
5900: }
1.30 www 5901:
1.766 albertel 5902: if ($thisallowed eq 'A') {
5903: return 'A';
1.814 raeburn 5904: } elsif ($thisallowed eq 'B') {
5905: return 'B';
1.766 albertel 5906: }
1.52 www 5907: return 'F';
1.232 www 5908: }
5909:
1.710 albertel 5910: sub split_uri_for_cond {
5911: my $uri=&deversion(&declutter(shift));
5912: my @uriparts=split(/\//,$uri);
5913: my $filename=pop(@uriparts);
5914: my $pathname=join('/',@uriparts);
5915: return ($pathname,$filename);
5916: }
1.232 www 5917: # --------------------------------------------------- Is a resource on the map?
5918:
5919: sub is_on_map {
1.710 albertel 5920: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5921: #Trying to find the conditional for the file
1.620 albertel 5922: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5923: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5924: if ($match) {
1.289 bowersj2 5925: return (1,$1);
5926: } else {
1.434 www 5927: return (0,0);
1.289 bowersj2 5928: }
1.12 www 5929: }
5930:
1.427 www 5931: # --------------------------------------------------------- Get symb from alias
5932:
5933: sub get_symb_from_alias {
5934: my $symb=shift;
5935: my ($map,$resid,$url)=&decode_symb($symb);
5936: # Already is a symb
5937: if ($url) { return $symb; }
5938: # Must be an alias
5939: my $aliassymb='';
5940: my %bighash;
1.620 albertel 5941: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5942: &GDBM_READER(),0640)) {
5943: my $rid=$bighash{'mapalias_'.$symb};
5944: if ($rid) {
5945: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5946: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5947: $resid,$bighash{'src_'.$rid});
1.427 www 5948: }
5949: untie %bighash;
5950: }
5951: return $aliassymb;
5952: }
5953:
1.12 www 5954: # ----------------------------------------------------------------- Define Role
5955:
5956: sub definerole {
5957: if (allowed('mcr','/')) {
5958: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5959: foreach my $role (split(':',$sysrole)) {
5960: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5961: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5962: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5963: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5964: return "refused:s:$crole&$cqual";
5965: }
5966: }
1.191 harris41 5967: }
1.800 albertel 5968: foreach my $role (split(':',$domrole)) {
5969: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5970: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5971: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5972: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5973: return "refused:d:$crole&$cqual";
5974: }
5975: }
1.191 harris41 5976: }
1.800 albertel 5977: foreach my $role (split(':',$courole)) {
5978: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5979: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5980: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5981: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5982: return "refused:c:$crole&$cqual";
5983: }
5984: }
1.191 harris41 5985: }
1.620 albertel 5986: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5987: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5988: "rolesdef_$rolename=".
5989: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5990: return reply($command,$env{'user.home'});
1.12 www 5991: } else {
5992: return 'refused';
5993: }
1.105 harris41 5994: }
5995:
5996: # ---------------- Make a metadata query against the network of library servers
5997:
5998: sub metadata_query {
1.244 matthew 5999: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6000: my %rhash;
1.845 albertel 6001: my %libserv = &all_library();
1.244 matthew 6002: my @server_list = (defined($server_array) ? @$server_array
6003: : keys(%libserv) );
6004: for my $server (@server_list) {
1.118 harris41 6005: unless ($custom or $customshow) {
6006: my $reply=&reply("querysend:".&escape($query),$server);
6007: $rhash{$server}=$reply;
6008: }
6009: else {
6010: my $reply=&reply("querysend:".&escape($query).':'.
6011: &escape($custom).':'.&escape($customshow),
6012: $server);
6013: $rhash{$server}=$reply;
6014: }
1.112 harris41 6015: }
1.118 harris41 6016: return \%rhash;
1.240 www 6017: }
6018:
6019: # ----------------------------------------- Send log queries and wait for reply
6020:
6021: sub log_query {
6022: my ($uname,$udom,$query,%filters)=@_;
6023: my $uhome=&homeserver($uname,$udom);
6024: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6025: my $uhost=&hostname($uhome);
1.800 albertel 6026: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6027: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6028: $uhome);
1.479 albertel 6029: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6030: return get_query_reply($queryid);
6031: }
6032:
1.818 raeburn 6033: # -------------------------- Update MySQL table for portfolio file
6034:
6035: sub update_portfolio_table {
1.821 raeburn 6036: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6037: if ($group ne '') {
6038: $file_name =~s /^\Q$group\E//;
6039: }
1.818 raeburn 6040: my $homeserver = &homeserver($uname,$udom);
6041: my $queryid=
1.821 raeburn 6042: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6043: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6044: my $reply = &get_query_reply($queryid);
6045: return $reply;
6046: }
6047:
1.899 raeburn 6048: # -------------------------- Update MySQL allusers table
6049:
6050: sub update_allusers_table {
6051: my ($uname,$udom,$names) = @_;
6052: my $homeserver = &homeserver($uname,$udom);
6053: my $queryid=
6054: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6055: 'lastname='.&escape($names->{'lastname'}).'%%'.
6056: 'firstname='.&escape($names->{'firstname'}).'%%'.
6057: 'middlename='.&escape($names->{'middlename'}).'%%'.
6058: 'generation='.&escape($names->{'generation'}).'%%'.
6059: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6060: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6061: return;
1.899 raeburn 6062: }
6063:
1.508 raeburn 6064: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6065:
6066: sub fetch_enrollment_query {
1.511 raeburn 6067: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6068: my $homeserver;
1.547 raeburn 6069: my $maxtries = 1;
1.508 raeburn 6070: if ($context eq 'automated') {
6071: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6072: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6073: } else {
6074: $homeserver = &homeserver($cnum,$dom);
6075: }
1.838 albertel 6076: my $host=&hostname($homeserver);
1.506 raeburn 6077: my $cmd = '';
1.1000 raeburn 6078: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6079: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6080: }
6081: $cmd =~ s/%%$//;
6082: $cmd = &escape($cmd);
6083: my $query = 'fetchenrollment';
1.620 albertel 6084: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6085: unless ($queryid=~/^\Q$host\E\_/) {
6086: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6087: return 'error: '.$queryid;
6088: }
1.506 raeburn 6089: my $reply = &get_query_reply($queryid);
1.547 raeburn 6090: my $tries = 1;
6091: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6092: $reply = &get_query_reply($queryid);
6093: $tries ++;
6094: }
1.526 raeburn 6095: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6096: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6097: } else {
1.901 albertel 6098: my @responses = split(/:/,$reply);
1.515 raeburn 6099: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6100: foreach my $line (@responses) {
6101: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6102: $$replyref{$key} = $value;
6103: }
6104: } else {
1.1117 foxr 6105: my $pathname = LONCAPA::tempdir();
1.800 albertel 6106: foreach my $line (@responses) {
6107: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6108: $$replyref{$key} = $value;
6109: if ($value > 0) {
1.800 albertel 6110: foreach my $item (@{$$affiliatesref{$key}}) {
6111: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6112: my $destname = $pathname.'/'.$filename;
6113: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6114: if ($xml_classlist =~ /^error/) {
6115: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6116: } else {
1.506 raeburn 6117: if ( open(FILE,">$destname") ) {
6118: print FILE &unescape($xml_classlist);
6119: close(FILE);
1.526 raeburn 6120: } else {
6121: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6122: }
6123: }
6124: }
6125: }
6126: }
6127: }
6128: return 'ok';
6129: }
6130: return 'error';
6131: }
6132:
1.242 www 6133: sub get_query_reply {
6134: my $queryid=shift;
1.1117 foxr 6135: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6136: my $reply='';
6137: for (1..100) {
6138: sleep 2;
6139: if (-e $replyfile.'.end') {
1.448 albertel 6140: if (open(my $fh,$replyfile)) {
1.904 albertel 6141: $reply = join('',<$fh>);
6142: close($fh);
1.240 www 6143: } else { return 'error: reply_file_error'; }
1.242 www 6144: return &unescape($reply);
6145: }
1.240 www 6146: }
1.242 www 6147: return 'timeout:'.$queryid;
1.240 www 6148: }
6149:
6150: sub courselog_query {
1.241 www 6151: #
6152: # possible filters:
6153: # url: url or symb
6154: # username
6155: # domain
6156: # action: view, submit, grade
6157: # start: timestamp
6158: # end: timestamp
6159: #
1.240 www 6160: my (%filters)=@_;
1.620 albertel 6161: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6162: if ($filters{'url'}) {
6163: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6164: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6165: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6166: }
1.620 albertel 6167: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6168: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6169: return &log_query($cname,$cdom,'courselog',%filters);
6170: }
6171:
6172: sub userlog_query {
1.858 raeburn 6173: #
6174: # possible filters:
6175: # action: log check role
6176: # start: timestamp
6177: # end: timestamp
6178: #
1.240 www 6179: my ($uname,$udom,%filters)=@_;
6180: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6181: }
6182:
1.506 raeburn 6183: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6184:
6185: sub auto_run {
1.508 raeburn 6186: my ($cnum,$cdom) = @_;
1.876 raeburn 6187: my $response = 0;
6188: my $settings;
6189: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6190: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6191: $settings = $domconfig{'autoenroll'};
6192: if ($settings->{'run'} eq '1') {
6193: $response = 1;
6194: }
6195: } else {
1.934 raeburn 6196: my $homeserver;
6197: if (&is_course($cdom,$cnum)) {
6198: $homeserver = &homeserver($cnum,$cdom);
6199: } else {
6200: $homeserver = &domain($cdom,'primary');
6201: }
6202: if ($homeserver ne 'no_host') {
6203: $response = &reply('autorun:'.$cdom,$homeserver);
6204: }
1.876 raeburn 6205: }
1.506 raeburn 6206: return $response;
6207: }
1.776 albertel 6208:
1.506 raeburn 6209: sub auto_get_sections {
1.508 raeburn 6210: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6211: my $homeserver;
6212: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6213: $homeserver = &homeserver($cnum,$cdom);
6214: }
6215: if (!defined($homeserver)) {
6216: if ($cdom =~ /^$match_domain$/) {
6217: $homeserver = &domain($cdom,'primary');
6218: }
6219: }
6220: my @secs;
6221: if (defined($homeserver)) {
6222: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6223: unless ($response eq 'refused') {
6224: @secs = split(/:/,$response);
6225: }
1.506 raeburn 6226: }
6227: return @secs;
6228: }
1.776 albertel 6229:
1.506 raeburn 6230: sub auto_new_course {
1.1099 raeburn 6231: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6232: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6233: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6234: return $response;
6235: }
1.776 albertel 6236:
1.506 raeburn 6237: sub auto_validate_courseID {
1.508 raeburn 6238: my ($cnum,$cdom,$inst_course_id) = @_;
6239: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6240: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6241: return $response;
6242: }
1.776 albertel 6243:
1.1007 raeburn 6244: sub auto_validate_instcode {
1.1020 raeburn 6245: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6246: my ($homeserver,$response);
6247: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6248: $homeserver = &homeserver($cnum,$cdom);
6249: }
6250: if (!defined($homeserver)) {
6251: if ($cdom =~ /^$match_domain$/) {
6252: $homeserver = &domain($cdom,'primary');
6253: }
6254: }
1.1065 raeburn 6255: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6256: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6257: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6258: return ($outcome,$description);
1.1007 raeburn 6259: }
6260:
1.506 raeburn 6261: sub auto_create_password {
1.873 raeburn 6262: my ($cnum,$cdom,$authparam,$udom) = @_;
6263: my ($homeserver,$response);
1.506 raeburn 6264: my $create_passwd = 0;
6265: my $authchk = '';
1.873 raeburn 6266: if ($udom =~ /^$match_domain$/) {
6267: $homeserver = &domain($udom,'primary');
6268: }
6269: if ($homeserver eq '') {
6270: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6271: $homeserver = &homeserver($cnum,$cdom);
6272: }
6273: }
6274: if ($homeserver eq '') {
6275: $authchk = 'nodomain';
1.506 raeburn 6276: } else {
1.873 raeburn 6277: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6278: if ($response eq 'refused') {
6279: $authchk = 'refused';
6280: } else {
1.901 albertel 6281: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6282: }
1.506 raeburn 6283: }
6284: return ($authparam,$create_passwd,$authchk);
6285: }
6286:
1.706 raeburn 6287: sub auto_photo_permission {
6288: my ($cnum,$cdom,$students) = @_;
6289: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6290: my ($outcome,$perm_reqd,$conditions) =
6291: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6292: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6293: return (undef,undef);
6294: }
1.706 raeburn 6295: return ($outcome,$perm_reqd,$conditions);
6296: }
6297:
6298: sub auto_checkphotos {
6299: my ($uname,$udom,$pid) = @_;
6300: my $homeserver = &homeserver($uname,$udom);
6301: my ($result,$resulttype);
6302: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6303: &escape($uname).':'.&escape($pid),
6304: $homeserver));
1.709 albertel 6305: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6306: return (undef,undef);
6307: }
1.706 raeburn 6308: if ($outcome) {
6309: ($result,$resulttype) = split(/:/,$outcome);
6310: }
6311: return ($result,$resulttype);
6312: }
6313:
6314: sub auto_photochoice {
6315: my ($cnum,$cdom) = @_;
6316: my $homeserver = &homeserver($cnum,$cdom);
6317: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6318: &escape($cdom),
6319: $homeserver)));
1.709 albertel 6320: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6321: return (undef,undef);
6322: }
1.706 raeburn 6323: return ($update,$comment);
6324: }
6325:
6326: sub auto_photoupdate {
6327: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6328: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6329: my $host=&hostname($homeserver);
1.706 raeburn 6330: my $cmd = '';
6331: my $maxtries = 1;
1.800 albertel 6332: foreach my $affiliate (keys(%{$affiliatesref})) {
6333: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6334: }
6335: $cmd =~ s/%%$//;
6336: $cmd = &escape($cmd);
6337: my $query = 'institutionalphotos';
6338: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6339: unless ($queryid=~/^\Q$host\E\_/) {
6340: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6341: return 'error: '.$queryid;
6342: }
6343: my $reply = &get_query_reply($queryid);
6344: my $tries = 1;
6345: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6346: $reply = &get_query_reply($queryid);
6347: $tries ++;
6348: }
6349: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6350: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6351: } else {
6352: my @responses = split(/:/,$reply);
6353: my $outcome = shift(@responses);
6354: foreach my $item (@responses) {
6355: my ($key,$value) = split(/=/,$item);
6356: $$photo{$key} = $value;
6357: }
6358: return $outcome;
6359: }
6360: return 'error';
6361: }
6362:
1.521 raeburn 6363: sub auto_instcode_format {
1.793 albertel 6364: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6365: $cat_order) = @_;
1.521 raeburn 6366: my $courses = '';
1.772 raeburn 6367: my @homeservers;
1.521 raeburn 6368: if ($caller eq 'global') {
1.841 albertel 6369: my %servers = &get_servers($codedom,'library');
6370: foreach my $tryserver (keys(%servers)) {
6371: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6372: push(@homeservers,$tryserver);
6373: }
1.584 raeburn 6374: }
1.1022 raeburn 6375: } elsif ($caller eq 'requests') {
6376: if ($codedom =~ /^$match_domain$/) {
6377: my $chome = &domain($codedom,'primary');
6378: unless ($chome eq 'no_host') {
6379: push(@homeservers,$chome);
6380: }
6381: }
1.521 raeburn 6382: } else {
1.772 raeburn 6383: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6384: }
1.793 albertel 6385: foreach my $code (keys(%{$instcodes})) {
6386: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6387: }
6388: chop($courses);
1.772 raeburn 6389: my $ok_response = 0;
6390: my $response;
6391: while (@homeservers > 0 && $ok_response == 0) {
6392: my $server = shift(@homeservers);
6393: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6394: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6395: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6396: split(/:/,$response);
1.772 raeburn 6397: %{$codes} = (%{$codes},&str2hash($codes_str));
6398: push(@{$codetitles},&str2array($codetitles_str));
6399: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6400: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6401: $ok_response = 1;
6402: }
6403: }
6404: if ($ok_response) {
1.521 raeburn 6405: return 'ok';
1.772 raeburn 6406: } else {
6407: return $response;
1.521 raeburn 6408: }
6409: }
6410:
1.792 raeburn 6411: sub auto_instcode_defaults {
6412: my ($domain,$returnhash,$code_order) = @_;
6413: my @homeservers;
1.841 albertel 6414:
6415: my %servers = &get_servers($domain,'library');
6416: foreach my $tryserver (keys(%servers)) {
6417: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6418: push(@homeservers,$tryserver);
6419: }
1.792 raeburn 6420: }
1.841 albertel 6421:
1.792 raeburn 6422: my $response;
1.841 albertel 6423: foreach my $server (@homeservers) {
1.792 raeburn 6424: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6425: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6426:
6427: foreach my $pair (split(/\&/,$response)) {
6428: my ($name,$value)=split(/\=/,$pair);
6429: if ($name eq 'code_order') {
6430: @{$code_order} = split(/\&/,&unescape($value));
6431: } else {
6432: $returnhash->{&unescape($name)}=&unescape($value);
6433: }
6434: }
6435: return 'ok';
1.792 raeburn 6436: }
1.841 albertel 6437:
6438: return $response;
1.1003 raeburn 6439: }
6440:
6441: sub auto_possible_instcodes {
1.1007 raeburn 6442: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6443: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6444: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6445: return;
6446: }
1.1003 raeburn 6447: my (@homeservers,$uhome);
6448: if (defined(&domain($domain,'primary'))) {
6449: $uhome=&domain($domain,'primary');
6450: push(@homeservers,&domain($domain,'primary'));
6451: } else {
6452: my %servers = &get_servers($domain,'library');
6453: foreach my $tryserver (keys(%servers)) {
6454: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6455: push(@homeservers,$tryserver);
6456: }
6457: }
6458: }
6459: my $response;
6460: foreach my $server (@homeservers) {
6461: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6462: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6463: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6464: split(':',$response);
6465: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6466: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6467: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6468: my ($name,$value)=split('=',$item);
6469: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6470: }
6471: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6472: my ($name,$value)=split('=',$item);
6473: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6474: }
6475: return 'ok';
6476: }
6477: return $response;
6478: }
1.792 raeburn 6479:
1.1010 raeburn 6480: sub auto_courserequest_checks {
6481: my ($dom) = @_;
1.1020 raeburn 6482: my ($homeserver,%validations);
6483: if ($dom =~ /^$match_domain$/) {
6484: $homeserver = &domain($dom,'primary');
6485: }
6486: unless ($homeserver eq 'no_host') {
6487: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6488: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6489: my @items = split(/&/,$response);
6490: foreach my $item (@items) {
6491: my ($key,$value) = split('=',$item);
6492: $validations{&unescape($key)} = &thaw_unescape($value);
6493: }
6494: }
6495: }
1.1010 raeburn 6496: return %validations;
6497: }
6498:
1.1020 raeburn 6499: sub auto_courserequest_validation {
6500: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6501: my ($homeserver,$response);
6502: if ($dom =~ /^$match_domain$/) {
6503: $homeserver = &domain($dom,'primary');
6504: }
6505: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6506:
1.1020 raeburn 6507: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6508: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6509: ':'.&escape($instcode).':'.&escape($instseclist),
6510: $homeserver));
6511: }
6512: return $response;
6513: }
6514:
1.777 albertel 6515: sub auto_validate_class_sec {
1.918 raeburn 6516: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6517: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6518: my $ownerlist;
6519: if (ref($owners) eq 'ARRAY') {
6520: $ownerlist = join(',',@{$owners});
6521: } else {
6522: $ownerlist = $owners;
6523: }
1.773 raeburn 6524: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6525: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6526: return $response;
6527: }
6528:
1.679 raeburn 6529: # ------------------------------------------------------- Course Group routines
6530:
6531: sub get_coursegroups {
1.809 raeburn 6532: my ($cdom,$cnum,$group,$namespace) = @_;
6533: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6534: }
6535:
1.679 raeburn 6536: sub modify_coursegroup {
6537: my ($cdom,$cnum,$groupsettings) = @_;
6538: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6539: }
6540:
1.809 raeburn 6541: sub toggle_coursegroup_status {
6542: my ($cdom,$cnum,$group,$action) = @_;
6543: my ($from_namespace,$to_namespace);
6544: if ($action eq 'delete') {
6545: $from_namespace = 'coursegroups';
6546: $to_namespace = 'deleted_groups';
6547: } else {
6548: $from_namespace = 'deleted_groups';
6549: $to_namespace = 'coursegroups';
6550: }
6551: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6552: if (my $tmp = &error(%curr_group)) {
6553: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6554: return ('read error',$tmp);
6555: } else {
6556: my %savedsettings = %curr_group;
1.809 raeburn 6557: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6558: my $deloutcome;
6559: if ($result eq 'ok') {
1.809 raeburn 6560: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6561: } else {
6562: return ('write error',$result);
6563: }
6564: if ($deloutcome eq 'ok') {
6565: return 'ok';
6566: } else {
6567: return ('delete error',$deloutcome);
6568: }
6569: }
6570: }
6571:
1.679 raeburn 6572: sub modify_group_roles {
1.957 raeburn 6573: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6574: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6575: my $role = 'gr/'.&escape($userprivs);
6576: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6577: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6578: if ($result eq 'ok') {
6579: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6580: }
1.679 raeburn 6581: return $result;
6582: }
6583:
6584: sub modify_coursegroup_membership {
6585: my ($cdom,$cnum,$membership) = @_;
6586: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6587: return $result;
6588: }
6589:
1.682 raeburn 6590: sub get_active_groups {
6591: my ($udom,$uname,$cdom,$cnum) = @_;
6592: my $now = time;
6593: my %groups = ();
6594: foreach my $key (keys(%env)) {
1.811 albertel 6595: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6596: my ($start,$end) = split(/\./,$env{$key});
6597: if (($end!=0) && ($end<$now)) { next; }
6598: if (($start!=0) && ($start>$now)) { next; }
6599: if ($1 eq $cdom && $2 eq $cnum) {
6600: $groups{$3} = $env{$key} ;
6601: }
6602: }
6603: }
6604: return %groups;
6605: }
6606:
1.683 raeburn 6607: sub get_group_membership {
6608: my ($cdom,$cnum,$group) = @_;
6609: return(&dump('groupmembership',$cdom,$cnum,$group));
6610: }
6611:
6612: sub get_users_groups {
6613: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6614: my @usersgroups;
1.683 raeburn 6615: my $cachetime=1800;
6616:
6617: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6618: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6619: if (defined($cached)) {
1.734 albertel 6620: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6621: } else {
6622: $grouplist = '';
1.816 raeburn 6623: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6624: my $extra = &freeze_escape({'skipcheck' => 1});
6625: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6626: my $access_end = $env{'course.'.$courseid.
6627: '.default_enrollment_end_date'};
6628: my $now = time;
6629: foreach my $key (keys(%roleshash)) {
6630: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6631: my $group = $1;
6632: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6633: my $start = $2;
6634: my $end = $1;
6635: if ($start == -1) { next; } # deleted from group
6636: if (($start!=0) && ($start>$now)) { next; }
6637: if (($end!=0) && ($end<$now)) {
6638: if ($access_end && $access_end < $now) {
6639: if ($access_end - $end < 86400) {
6640: push(@usersgroups,$group);
1.733 raeburn 6641: }
6642: }
1.817 raeburn 6643: next;
1.733 raeburn 6644: }
1.817 raeburn 6645: push(@usersgroups,$group);
1.683 raeburn 6646: }
6647: }
6648: }
1.817 raeburn 6649: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6650: $grouplist = join(':',@usersgroups);
6651: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6652: }
1.733 raeburn 6653: return @usersgroups;
1.683 raeburn 6654: }
6655:
6656: sub devalidate_getgroups_cache {
6657: my ($udom,$uname,$cdom,$cnum)=@_;
6658: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6659:
1.683 raeburn 6660: my $hashid="$udom:$uname:$courseid";
6661: &devalidate_cache_new('getgroups',$hashid);
6662: }
6663:
1.12 www 6664: # ------------------------------------------------------------------ Plain Text
6665:
6666: sub plaintext {
1.988 raeburn 6667: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6668: if ($short =~ m{^cr/}) {
1.758 albertel 6669: return (split('/',$short))[-1];
6670: }
1.742 raeburn 6671: if (!defined($cid)) {
6672: $cid = $env{'request.course.id'};
6673: }
6674: my %rolenames = (
1.1008 raeburn 6675: Course => 'std',
6676: Community => 'alt1',
1.742 raeburn 6677: );
1.1037 raeburn 6678: if ($cid ne '') {
6679: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6680: unless ($forcedefault) {
6681: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6682: &Apache::lonlocal::mt_escape(\$roletext);
6683: return &Apache::lonlocal::mt($roletext);
6684: }
6685: }
6686: }
6687: if ((defined($type)) && (defined($rolenames{$type})) &&
6688: (defined($rolenames{$type})) &&
6689: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6690: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6691: } elsif ($cid ne '') {
6692: my $crstype = $env{'course.'.$cid.'.type'};
6693: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6694: (defined($prp{$short}{$rolenames{$crstype}}))) {
6695: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6696: }
1.742 raeburn 6697: }
1.1037 raeburn 6698: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6699: }
6700:
6701: # ----------------------------------------------------------------- Assign Role
6702:
6703: sub assignrole {
1.957 raeburn 6704: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6705: $context)=@_;
1.21 www 6706: my $mrole;
6707: if ($role =~ /^cr\//) {
1.393 www 6708: my $cwosec=$url;
1.811 albertel 6709: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6710: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6711: my $refused = 1;
6712: if ($context eq 'requestcourses') {
6713: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6714: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6715: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6716: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6717: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6718: if ($crsenv{'internal.courseowner'} eq
6719: $env{'user.name'}.':'.$env{'user.domain'}) {
6720: $refused = '';
6721: }
6722: }
6723: }
6724: }
6725: }
6726: if ($refused) {
6727: &logthis('Refused custom assignrole: '.
6728: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6729: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6730: return 'refused';
6731: }
1.104 www 6732: }
1.21 www 6733: $mrole='cr';
1.678 raeburn 6734: } elsif ($role =~ /^gr\//) {
6735: my $cwogrp=$url;
1.811 albertel 6736: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6737: unless (&allowed('mdg',$cwogrp)) {
6738: &logthis('Refused group assignrole: '.
6739: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6740: $env{'user.name'}.' at '.$env{'user.domain'});
6741: return 'refused';
6742: }
6743: $mrole='gr';
1.21 www 6744: } else {
1.82 www 6745: my $cwosec=$url;
1.811 albertel 6746: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6747: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6748: my $refused;
6749: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6750: if (!(&allowed('c'.$role,$url))) {
6751: $refused = 1;
6752: }
6753: } else {
6754: $refused = 1;
6755: }
1.947 raeburn 6756: if ($refused) {
1.1045 raeburn 6757: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6758: if (!$selfenroll && $context eq 'course') {
6759: my %crsenv;
6760: if ($role eq 'cc' || $role eq 'co') {
6761: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6762: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6763: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6764: if ($crsenv{'internal.courseowner'} eq
6765: $env{'user.name'}.':'.$env{'user.domain'}) {
6766: $refused = '';
6767: }
6768: }
6769: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6770: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6771: if ($crsenv{'internal.courseowner'} eq
6772: $env{'user.name'}.':'.$env{'user.domain'}) {
6773: $refused = '';
6774: }
6775: }
6776: }
6777: }
6778: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6779: $refused = '';
1.1017 raeburn 6780: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6781: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6782: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6783: my $wrongcc;
6784: if ($cnum =~ /^$match_community$/) {
6785: $wrongcc = 1 if ($role eq 'cc');
6786: } else {
6787: $wrongcc = 1 if ($role eq 'co');
6788: }
6789: unless ($wrongcc) {
6790: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6791: if ($crsenv{'internal.courseowner'} eq
6792: $env{'user.name'}.':'.$env{'user.domain'}) {
6793: $refused = '';
6794: }
1.1017 raeburn 6795: }
6796: }
6797: }
6798: if ($refused) {
1.947 raeburn 6799: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6800: ' '.$role.' '.$end.' '.$start.' by '.
6801: $env{'user.name'}.' at '.$env{'user.domain'});
6802: return 'refused';
6803: }
1.932 raeburn 6804: }
1.104 www 6805: }
1.21 www 6806: $mrole=$role;
6807: }
1.620 albertel 6808: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6809: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6810: if ($end) { $command.='_'.$end; }
1.21 www 6811: if ($start) {
6812: if ($end) {
1.81 www 6813: $command.='_'.$start;
1.21 www 6814: } else {
1.81 www 6815: $command.='_0_'.$start;
1.21 www 6816: }
6817: }
1.739 raeburn 6818: my $origstart = $start;
6819: my $origend = $end;
1.957 raeburn 6820: my $delflag;
1.357 www 6821: # actually delete
6822: if ($deleteflag) {
1.373 www 6823: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6824: # modify command to delete the role
1.620 albertel 6825: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6826: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6827: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6828: # set start and finish to negative values for userrolelog
6829: $start=-1;
6830: $end=-1;
1.957 raeburn 6831: $delflag = 1;
1.357 www 6832: }
6833: }
6834: # send command
1.349 www 6835: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6836: # log new user role if status is ok
1.349 www 6837: if ($answer eq 'ok') {
1.663 raeburn 6838: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6839: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6840: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6841: unless ($role =~ /^gr/) {
6842: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6843: $origstart,$selfenroll,$context);
1.739 raeburn 6844: }
1.1053 raeburn 6845: if ($role eq 'cc') {
6846: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6847: }
1.349 www 6848: }
6849: return $answer;
1.169 harris41 6850: }
6851:
1.1053 raeburn 6852: sub autoupdate_coowners {
6853: my ($url,$end,$start,$uname,$udom) = @_;
6854: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6855: if (($cdom ne '') && ($cnum ne '')) {
6856: my $now = time;
6857: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6858: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6859: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6860: my $instcode = $coursehash{'internal.coursecode'};
6861: if ($instcode ne '') {
1.1056 raeburn 6862: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6863: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6864: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6865: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6866: if ($result eq 'valid') {
6867: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6868: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6869: push(@newcoowners,$coowner);
6870: }
6871: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6872: push(@newcoowners,$uname.':'.$udom);
6873: }
6874: @newcoowners = sort(@newcoowners);
6875: } else {
6876: push(@newcoowners,$uname.':'.$udom);
6877: }
6878: } else {
6879: if ($coursehash{'internal.co-owners'}) {
6880: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6881: unless ($coowner eq $uname.':'.$udom) {
6882: push(@newcoowners,$coowner);
6883: }
6884: }
6885: unless (@newcoowners > 0) {
6886: $delcoowners = 1;
6887: $coowners = '';
6888: }
6889: }
6890: }
6891: if (@newcoowners || $delcoowners) {
6892: &store_coowners($cdom,$cnum,$coursehash{'home'},
6893: $delcoowners,@newcoowners);
6894: }
6895: }
6896: }
6897: }
6898: }
6899: }
6900: }
6901:
6902: sub store_coowners {
6903: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6904: my $cid = $cdom.'_'.$cnum;
6905: my ($coowners,$delresult,$putresult);
6906: if (@newcoowners) {
6907: $coowners = join(',',@newcoowners);
6908: my %coownershash = (
6909: 'internal.co-owners' => $coowners,
6910: );
6911: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6912: if ($putresult eq 'ok') {
6913: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6914: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6915: }
6916: }
6917: }
6918: if ($delcoowners) {
6919: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6920: if ($delresult eq 'ok') {
6921: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6922: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6923: }
6924: }
6925: }
6926: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6927: my %crsinfo =
6928: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6929: if (ref($crsinfo{$cid}) eq 'HASH') {
6930: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6931: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6932: }
6933: }
6934: }
6935:
1.169 harris41 6936: # -------------------------------------------------- Modify user authentication
1.197 www 6937: # Overrides without validation
6938:
1.169 harris41 6939: sub modifyuserauth {
6940: my ($udom,$uname,$umode,$upass)=@_;
6941: my $uhome=&homeserver($uname,$udom);
1.197 www 6942: unless (&allowed('mau',$udom)) { return 'refused'; }
6943: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6944: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6945: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6946: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6947: &escape($upass),$uhome);
1.620 albertel 6948: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6949: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6950: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6951: &log($udom,,$uname,$uhome,
1.620 albertel 6952: 'Authentication changed by '.$env{'user.domain'}.', '.
6953: $env{'user.name'}.', '.$umode.
1.197 www 6954: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6955: unless ($reply eq 'ok') {
1.197 www 6956: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6957: return 'error: '.$reply;
6958: }
1.170 harris41 6959: return 'ok';
1.80 www 6960: }
6961:
1.81 www 6962: # --------------------------------------------------------------- Modify a user
1.80 www 6963:
1.81 www 6964: sub modifyuser {
1.206 matthew 6965: my ($udom, $uname, $uid,
6966: $umode, $upass, $first,
6967: $middle, $last, $gene,
1.1058 raeburn 6968: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6969: $udom= &LONCAPA::clean_domain($udom);
6970: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6971: my $showcandelete = 'none';
6972: if (ref($candelete) eq 'ARRAY') {
6973: if (@{$candelete} > 0) {
6974: $showcandelete = join(', ',@{$candelete});
6975: }
6976: }
1.81 www 6977: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6978: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6979: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6980: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6981: ' desiredhome not specified').
1.620 albertel 6982: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6983: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6984: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6985: my $newuser;
6986: if ($uhome eq 'no_host') {
6987: $newuser = 1;
6988: }
1.80 www 6989: # ----------------------------------------------------------------- Create User
1.406 albertel 6990: if (($uhome eq 'no_host') &&
6991: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6992: my $unhome='';
1.844 albertel 6993: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6994: $unhome = $desiredhome;
1.620 albertel 6995: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6996: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6997: } else { # load balancing routine for determining $unhome
1.81 www 6998: my $loadm=10000000;
1.841 albertel 6999: my %servers = &get_servers($udom,'library');
7000: foreach my $tryserver (keys(%servers)) {
7001: my $answer=reply('load',$tryserver);
7002: if (($answer=~/\d+/) && ($answer<$loadm)) {
7003: $loadm=$answer;
7004: $unhome=$tryserver;
7005: }
1.80 www 7006: }
7007: }
7008: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7009: return 'error: unable to find a home server for '.$uname.
7010: ' in domain '.$udom;
1.80 www 7011: }
7012: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7013: &escape($upass),$unhome);
7014: unless ($reply eq 'ok') {
7015: return 'error: '.$reply;
7016: }
1.230 stredwic 7017: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7018: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7019: return 'error: unable verify users home machine.';
1.80 www 7020: }
1.209 matthew 7021: } # End of creation of new user
1.80 www 7022: # ---------------------------------------------------------------------- Add ID
7023: if ($uid) {
7024: $uid=~tr/A-Z/a-z/;
7025: my %uidhash=&idrget($udom,$uname);
1.196 www 7026: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7027: && (!$forceid)) {
1.80 www 7028: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7029: return 'error: user id "'.$uid.'" does not match '.
7030: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7031: }
7032: } else {
7033: &idput($udom,($uname => $uid));
7034: }
7035: }
7036: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7037: my @tmp=&get('environment',
1.899 raeburn 7038: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7039: 'permanentemail','inststatus'],
1.134 albertel 7040: $udom,$uname);
1.1075 raeburn 7041: my (%names,%oldnames);
1.313 matthew 7042: if ($tmp[0] =~ m/^error:.*/) {
7043: %names=();
7044: } else {
7045: %names = @tmp;
1.1075 raeburn 7046: %oldnames = %names;
1.313 matthew 7047: }
1.388 www 7048: #
1.1058 raeburn 7049: # If name, email and/or uid are blank (e.g., because an uploaded file
7050: # of users did not contain them), do not overwrite existing values
7051: # unless field is in $candelete array ref.
7052: #
7053:
7054: my @fields = ('firstname','middlename','lastname','generation',
7055: 'permanentemail','id');
7056: my %newvalues;
7057: if (ref($candelete) eq 'ARRAY') {
7058: foreach my $field (@fields) {
7059: if (grep(/^\Q$field\E$/,@{$candelete})) {
7060: if ($field eq 'firstname') {
7061: $names{$field} = $first;
7062: } elsif ($field eq 'middlename') {
7063: $names{$field} = $middle;
7064: } elsif ($field eq 'lastname') {
7065: $names{$field} = $last;
7066: } elsif ($field eq 'generation') {
7067: $names{$field} = $gene;
7068: } elsif ($field eq 'permanentemail') {
7069: $names{$field} = $email;
7070: } elsif ($field eq 'id') {
7071: $names{$field} = $uid;
7072: }
7073: }
7074: }
7075: }
1.388 www 7076: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7077: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7078: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7079: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7080: if ($email) {
7081: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7082: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7083: }
1.899 raeburn 7084: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7085: if (defined($inststatus)) {
7086: $names{'inststatus'} = '';
7087: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7088: if (ref($usertypes) eq 'HASH') {
7089: my @okstatuses;
7090: foreach my $item (split(/:/,$inststatus)) {
7091: if (defined($usertypes->{$item})) {
7092: push(@okstatuses,$item);
7093: }
7094: }
7095: if (@okstatuses) {
7096: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7097: }
7098: }
7099: }
1.1075 raeburn 7100: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7101: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7102: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7103: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7104: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7105: } else {
7106: $logmsg .= ' during self creation';
7107: }
1.1075 raeburn 7108: my $changed;
7109: if ($newuser) {
7110: $changed = 1;
7111: } else {
7112: foreach my $field (@fields) {
7113: if ($names{$field} ne $oldnames{$field}) {
7114: $changed = 1;
7115: last;
7116: }
7117: }
7118: }
7119: unless ($changed) {
7120: $logmsg = 'No changes in user information needed for: '.$logmsg;
7121: &logthis($logmsg);
7122: return 'ok';
7123: }
7124: my $reply = &put('environment', \%names, $udom,$uname);
7125: if ($reply ne 'ok') {
7126: return 'error: '.$reply;
7127: }
1.1087 raeburn 7128: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7129: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7130: }
1.1075 raeburn 7131: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7132: &devalidate_cache_new('namescache',$uname.':'.$udom);
7133: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7134: &logthis($logmsg);
1.134 albertel 7135: return 'ok';
1.80 www 7136: }
7137:
1.81 www 7138: # -------------------------------------------------------------- Modify student
1.80 www 7139:
1.81 www 7140: sub modifystudent {
7141: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7142: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7143: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7144: if (!$cid) {
1.620 albertel 7145: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7146: return 'not_in_class';
7147: }
1.80 www 7148: }
7149: # --------------------------------------------------------------- Make the user
1.81 www 7150: my $reply=&modifyuser
1.209 matthew 7151: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7152: $desiredhome,$email,$inststatus);
1.80 www 7153: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7154: # This will cause &modify_student_enrollment to get the uid from the
7155: # students environment
7156: $uid = undef if (!$forceid);
1.455 albertel 7157: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7158: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7159: return $reply;
7160: }
7161:
7162: sub modify_student_enrollment {
1.957 raeburn 7163: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7164: my ($cdom,$cnum,$chome);
7165: if (!$cid) {
1.620 albertel 7166: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7167: return 'not_in_class';
7168: }
1.620 albertel 7169: $cdom=$env{'course.'.$cid.'.domain'};
7170: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7171: } else {
7172: ($cdom,$cnum)=split(/_/,$cid);
7173: }
1.620 albertel 7174: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7175: if (!$chome) {
1.457 raeburn 7176: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7177: }
1.455 albertel 7178: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7179: # Make sure the user exists
1.81 www 7180: my $uhome=&homeserver($uname,$udom);
7181: if (($uhome eq '') || ($uhome eq 'no_host')) {
7182: return 'error: no such user';
7183: }
1.297 matthew 7184: # Get student data if we were not given enough information
7185: if (!defined($first) || $first eq '' ||
7186: !defined($last) || $last eq '' ||
7187: !defined($uid) || $uid eq '' ||
7188: !defined($middle) || $middle eq '' ||
7189: !defined($gene) || $gene eq '') {
1.294 matthew 7190: # They did not supply us with enough data to enroll the student, so
7191: # we need to pick up more information.
1.297 matthew 7192: my %tmp = &get('environment',
1.294 matthew 7193: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7194: ,$udom,$uname);
7195:
1.800 albertel 7196: #foreach my $key (keys(%tmp)) {
7197: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7198: #}
1.294 matthew 7199: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7200: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7201: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7202: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7203: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7204: }
1.556 albertel 7205: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7206: my $reply=cput('classlist',
7207: {"$uname:$udom" =>
1.515 raeburn 7208: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7209: $cdom,$cnum);
1.81 www 7210: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7211: return 'error: '.$reply;
1.652 albertel 7212: } else {
7213: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7214: }
1.297 matthew 7215: # Add student role to user
1.83 www 7216: my $uurl='/'.$cid;
1.81 www 7217: $uurl=~s/\_/\//g;
7218: if ($usec) {
7219: $uurl.='/'.$usec;
7220: }
1.957 raeburn 7221: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7222: }
7223:
1.556 albertel 7224: sub format_name {
7225: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7226: my $name;
7227: if ($first ne 'lastname') {
7228: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7229: } else {
7230: if ($lastname=~/\S/) {
7231: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7232: $name=~s/\s+,/,/;
7233: } else {
7234: $name.= $firstname.' '.$middlename.' '.$generation;
7235: }
7236: }
7237: $name=~s/^\s+//;
7238: $name=~s/\s+$//;
7239: $name=~s/\s+/ /g;
7240: return $name;
7241: }
7242:
1.84 www 7243: # ------------------------------------------------- Write to course preferences
7244:
7245: sub writecoursepref {
7246: my ($courseid,%prefs)=@_;
7247: $courseid=~s/^\///;
7248: $courseid=~s/\_/\//g;
7249: my ($cdomain,$cnum)=split(/\//,$courseid);
7250: my $chome=homeserver($cnum,$cdomain);
7251: if (($chome eq '') || ($chome eq 'no_host')) {
7252: return 'error: no such course';
7253: }
7254: my $cstring='';
1.800 albertel 7255: foreach my $pref (keys(%prefs)) {
7256: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7257: }
1.84 www 7258: $cstring=~s/\&$//;
7259: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7260: }
7261:
7262: # ---------------------------------------------------------- Make/modify course
7263:
7264: sub createcourse {
1.741 raeburn 7265: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7266: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7267: $url=&declutter($url);
7268: my $cid='';
1.1028 raeburn 7269: if ($context eq 'requestcourses') {
7270: my $can_create = 0;
7271: my ($ownername,$ownerdom) = split(':',$course_owner);
7272: if ($udom eq $ownerdom) {
7273: if (&usertools_access($ownername,$ownerdom,$category,undef,
7274: $context)) {
7275: $can_create = 1;
7276: }
7277: } else {
7278: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7279: $category);
7280: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7281: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7282: if (@curr > 0) {
7283: my @options = qw(approval validate autolimit);
7284: my $optregex = join('|',@options);
7285: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7286: $can_create = 1;
7287: }
7288: }
7289: }
7290: }
7291: if ($can_create) {
7292: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7293: unless (&allowed('ccc',$udom)) {
7294: return 'refused';
7295: }
1.1017 raeburn 7296: }
7297: } else {
7298: return 'refused';
7299: }
1.1028 raeburn 7300: } elsif (!&allowed('ccc',$udom)) {
7301: return 'refused';
1.84 www 7302: }
1.1011 raeburn 7303: # --------------------------------------------------------------- Get Unique ID
7304: my $uname;
7305: if ($cnum =~ /^$match_courseid$/) {
7306: my $chome=&homeserver($cnum,$udom,'true');
7307: if (($chome eq '') || ($chome eq 'no_host')) {
7308: $uname = $cnum;
7309: } else {
1.1038 raeburn 7310: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7311: }
7312: } else {
1.1038 raeburn 7313: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7314: }
7315: return $uname if ($uname =~ /^error/);
7316: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7317: if (!defined($course_server)) {
7318: if (defined(&domain($udom,'primary'))) {
7319: $course_server = &domain($udom,'primary');
7320: } else {
7321: $course_server = $env{'user.home'};
7322: }
7323: }
7324: my %host_servers =
7325: &Apache::lonnet::get_servers($udom,'library');
7326: unless ($host_servers{$course_server}) {
7327: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7328: }
1.84 www 7329: # ------------------------------------------------------------- Make the course
7330: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7331: $course_server);
1.84 www 7332: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7333: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7334: if (($uhome eq '') || ($uhome eq 'no_host')) {
7335: return 'error: no such course';
7336: }
1.271 www 7337: # ----------------------------------------------------------------- Course made
1.516 raeburn 7338: # log existence
1.1029 raeburn 7339: my $now = time;
1.918 raeburn 7340: my $newcourse = {
7341: $udom.'_'.$uname => {
1.921 raeburn 7342: description => $description,
7343: inst_code => $inst_code,
7344: owner => $course_owner,
7345: type => $crstype,
1.1029 raeburn 7346: creator => $env{'user.name'}.':'.
7347: $env{'user.domain'},
7348: created => $now,
7349: context => $context,
1.918 raeburn 7350: },
7351: };
1.921 raeburn 7352: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7353: # set toplevel url
1.271 www 7354: my $topurl=$url;
7355: unless ($nonstandard) {
7356: # ------------------------------------------ For standard courses, make top url
7357: my $mapurl=&clutter($url);
1.278 www 7358: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7359: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7360: <map>
7361: <resource id="1" type="start"></resource>
7362: <resource id="2" src="$mapurl"></resource>
7363: <resource id="3" type="finish"></resource>
7364: <link index="1" from="1" to="2"></link>
7365: <link index="2" from="2" to="3"></link>
7366: </map>
7367: ENDINITMAP
7368: $topurl=&declutter(
1.638 albertel 7369: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7370: );
7371: }
7372: # ----------------------------------------------------------- Write preferences
1.84 www 7373: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7374: ('description' => $description,
7375: 'url' => $topurl,
7376: 'internal.creator' => $env{'user.name'}.':'.
7377: $env{'user.domain'},
7378: 'internal.created' => $now,
7379: 'internal.creationcontext' => $context)
7380: );
1.84 www 7381: return '/'.$udom.'/'.$uname;
7382: }
7383:
1.1011 raeburn 7384: # ------------------------------------------------------------------- Create ID
7385: sub generate_coursenum {
1.1038 raeburn 7386: my ($udom,$crstype) = @_;
1.1011 raeburn 7387: my $domdesc = &domain($udom);
7388: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7389: my $first;
7390: if ($crstype eq 'Community') {
7391: $first = '0';
7392: } else {
7393: $first = int(1+rand(9));
7394: }
7395: my $uname=$first.
1.1011 raeburn 7396: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7397: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7398: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7399: # ----------------------------------------------- Make sure that does not exist
7400: my $uhome=&homeserver($uname,$udom,'true');
7401: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7402: if ($crstype eq 'Community') {
7403: $first = '0';
7404: } else {
7405: $first = int(1+rand(9));
7406: }
7407: $uname=$first.
1.1011 raeburn 7408: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7409: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7410: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7411: $uhome=&homeserver($uname,$udom,'true');
7412: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7413: return 'error: unable to generate unique course-ID';
7414: }
7415: }
7416: return $uname;
7417: }
7418:
1.813 albertel 7419: sub is_course {
7420: my ($cdom,$cnum) = @_;
7421: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7422: undef,'.');
1.813 albertel 7423: if (exists($courses{$cdom.'_'.$cnum})) {
7424: return 1;
7425: }
7426: return 0;
7427: }
7428:
1.1015 raeburn 7429: sub store_userdata {
7430: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7431: my $result;
1.1016 raeburn 7432: if ($datakey ne '') {
1.1013 raeburn 7433: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7434: if ($udom eq '' || $uname eq '') {
7435: $udom = $env{'user.domain'};
7436: $uname = $env{'user.name'};
7437: }
7438: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7439: if (($uhome eq '') || ($uhome eq 'no_host')) {
7440: $result = 'error: no_host';
7441: } else {
7442: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7443: $storehash->{'host'} = $perlvar{'lonHostID'};
7444:
7445: my $namevalue='';
7446: foreach my $key (keys(%{$storehash})) {
7447: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7448: }
7449: $namevalue=~s/\&$//;
1.1105 raeburn 7450: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7451: $namevalue,$uhome);
1.1013 raeburn 7452: }
7453: } else {
7454: $result = 'error: data to store was not a hash reference';
7455: }
7456: } else {
7457: $result= 'error: invalid requestkey';
7458: }
7459: return $result;
7460: }
7461:
1.21 www 7462: # ---------------------------------------------------------- Assign Custom Role
7463:
7464: sub assigncustomrole {
1.957 raeburn 7465: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7466: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7467: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7468: }
7469:
7470: # ----------------------------------------------------------------- Revoke Role
7471:
7472: sub revokerole {
1.957 raeburn 7473: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7474: my $now=time;
1.965 raeburn 7475: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7476: }
7477:
7478: # ---------------------------------------------------------- Revoke Custom Role
7479:
7480: sub revokecustomrole {
1.957 raeburn 7481: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7482: my $now=time;
1.357 www 7483: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7484: $deleteflag,$selfenroll,$context);
1.17 www 7485: }
7486:
1.533 banghart 7487: # ------------------------------------------------------------ Disk usage
1.535 albertel 7488: sub diskusage {
1.955 raeburn 7489: my ($udom,$uname,$directorypath,$getpropath)=@_;
7490: $directorypath =~ s/\/$//;
7491: my $listing=&reply('du2:'.&escape($directorypath).':'
7492: .&escape($getpropath).':'.&escape($uname).':'
7493: .&escape($udom),homeserver($uname,$udom));
7494: if ($listing eq 'unknown_cmd') {
7495: if ($getpropath) {
7496: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7497: }
7498: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7499: }
1.514 albertel 7500: return $listing;
1.512 banghart 7501: }
7502:
1.566 banghart 7503: sub is_locked {
1.1096 raeburn 7504: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7505: my @check;
7506: my $is_locked;
1.1093 raeburn 7507: push (@check,$file_name);
1.613 albertel 7508: my %locked = &get('file_permissions',\@check,
1.620 albertel 7509: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7510: my ($tmp)=keys(%locked);
7511: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7512:
1.566 banghart 7513: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7514: $is_locked = 'false';
7515: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7516: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7517: $is_locked = 'true';
1.1096 raeburn 7518: if (ref($which) eq 'ARRAY') {
7519: push(@{$which},$entry);
7520: } else {
7521: last;
7522: }
1.745 raeburn 7523: }
7524: }
1.566 banghart 7525: } else {
7526: $is_locked = 'false';
7527: }
1.1093 raeburn 7528: return $is_locked;
1.566 banghart 7529: }
7530:
1.759 albertel 7531: sub declutter_portfile {
7532: my ($file) = @_;
1.833 albertel 7533: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7534: return $file;
7535: }
7536:
1.559 banghart 7537: # ------------------------------------------------------------- Mark as Read Only
7538:
7539: sub mark_as_readonly {
7540: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7541: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7542: my ($tmp)=keys(%current_permissions);
7543: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7544: foreach my $file (@{$files}) {
1.759 albertel 7545: $file = &declutter_portfile($file);
1.561 banghart 7546: push(@{$current_permissions{$file}},$what);
1.559 banghart 7547: }
1.613 albertel 7548: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7549: return;
7550: }
7551:
1.572 banghart 7552: # ------------------------------------------------------------Save Selected Files
7553:
7554: sub save_selected_files {
7555: my ($user, $path, @files) = @_;
7556: my $filename = $user."savedfiles";
1.573 banghart 7557: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7558: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7559: foreach my $file (@files) {
1.620 albertel 7560: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7561: }
7562: foreach my $file (@other_files) {
1.574 banghart 7563: print (OUT $file."\n");
1.572 banghart 7564: }
1.574 banghart 7565: close (OUT);
1.572 banghart 7566: return 'ok';
7567: }
7568:
1.574 banghart 7569: sub clear_selected_files {
7570: my ($user) = @_;
7571: my $filename = $user."savedfiles";
1.1117 foxr 7572: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7573: print (OUT undef);
7574: close (OUT);
7575: return ("ok");
7576: }
7577:
1.572 banghart 7578: sub files_in_path {
7579: my ($user, $path) = @_;
7580: my $filename = $user."savedfiles";
7581: my %return_files;
1.1117 foxr 7582: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7583: while (my $line_in = <IN>) {
1.574 banghart 7584: chomp ($line_in);
7585: my @paths_and_file = split (m!/!, $line_in);
7586: my $file_part = pop (@paths_and_file);
7587: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7588: $path_part.='/';
7589: my $path_and_file = $path_part.$file_part;
7590: if ($path_part eq $path) {
7591: $return_files{$file_part}= 'selected';
7592: }
7593: }
1.574 banghart 7594: close (IN);
7595: return (\%return_files);
1.572 banghart 7596: }
7597:
7598: # called in portfolio select mode, to show files selected NOT in current directory
7599: sub files_not_in_path {
7600: my ($user, $path) = @_;
7601: my $filename = $user."savedfiles";
7602: my @return_files;
7603: my $path_part;
1.1117 foxr 7604: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7605: while (my $line = <IN>) {
1.572 banghart 7606: #ok, I know it's clunky, but I want it to work
1.800 albertel 7607: my @paths_and_file = split(m|/|, $line);
7608: my $file_part = pop(@paths_and_file);
7609: chomp($file_part);
7610: my $path_part = join('/', @paths_and_file);
1.572 banghart 7611: $path_part .= '/';
7612: my $path_and_file = $path_part.$file_part;
7613: if ($path_part ne $path) {
1.800 albertel 7614: push(@return_files, ($path_and_file));
1.572 banghart 7615: }
7616: }
1.800 albertel 7617: close(OUT);
1.574 banghart 7618: return (@return_files);
1.572 banghart 7619: }
7620:
1.745 raeburn 7621: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7622:
1.745 raeburn 7623: sub get_portfile_permissions {
7624: my ($domain,$user) = @_;
1.613 albertel 7625: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7626: my ($tmp)=keys(%current_permissions);
7627: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7628: return \%current_permissions;
7629: }
7630:
7631: #---------------------------------------------Get portfolio file access controls
7632:
1.749 raeburn 7633: sub get_access_controls {
1.745 raeburn 7634: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7635: my %access;
7636: my $real_file = $file;
7637: $file =~ s/\.meta$//;
1.745 raeburn 7638: if (defined($file)) {
1.749 raeburn 7639: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7640: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7641: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7642: }
7643: }
1.745 raeburn 7644: } else {
1.749 raeburn 7645: foreach my $key (keys(%{$current_permissions})) {
7646: if ($key =~ /\0accesscontrol$/) {
7647: if (defined($group)) {
7648: if ($key !~ m-^\Q$group\E/-) {
7649: next;
7650: }
7651: }
7652: my ($fullpath) = split(/\0/,$key);
7653: if (ref($$current_permissions{$key}) eq 'HASH') {
7654: foreach my $control (keys(%{$$current_permissions{$key}})) {
7655: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7656: }
7657: }
7658: }
7659: }
7660: }
7661: return %access;
7662: }
7663:
7664: sub modify_access_controls {
7665: my ($file_name,$changes,$domain,$user)=@_;
7666: my ($outcome,$deloutcome);
7667: my %store_permissions;
7668: my %new_values;
7669: my %new_control;
7670: my %translation;
7671: my @deletions = ();
7672: my $now = time;
7673: if (exists($$changes{'activate'})) {
7674: if (ref($$changes{'activate'}) eq 'HASH') {
7675: my @newitems = sort(keys(%{$$changes{'activate'}}));
7676: my $numnew = scalar(@newitems);
7677: for (my $i=0; $i<$numnew; $i++) {
7678: my $newkey = $newitems[$i];
7679: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7680: if ($newkey =~ /^\d+:/) {
7681: $newkey =~ s/^(\d+)/$newid/;
7682: $translation{$1} = $newid;
7683: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7684: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7685: $translation{$1} = $newid;
7686: }
1.749 raeburn 7687: $new_values{$file_name."\0".$newkey} =
7688: $$changes{'activate'}{$newitems[$i]};
7689: $new_control{$newkey} = $now;
7690: }
7691: }
7692: }
7693: my %todelete;
7694: my %changed_items;
7695: foreach my $action ('delete','update') {
7696: if (exists($$changes{$action})) {
7697: if (ref($$changes{$action}) eq 'HASH') {
7698: foreach my $key (keys(%{$$changes{$action}})) {
7699: my ($itemnum) = ($key =~ /^([^:]+):/);
7700: if ($action eq 'delete') {
7701: $todelete{$itemnum} = 1;
7702: } else {
7703: $changed_items{$itemnum} = $key;
7704: }
7705: }
1.745 raeburn 7706: }
7707: }
1.749 raeburn 7708: }
7709: # get lock on access controls for file.
7710: my $lockhash = {
7711: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7712: ':'.$env{'user.domain'},
7713: };
7714: my $tries = 0;
7715: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7716:
7717: while (($gotlock ne 'ok') && $tries <3) {
7718: $tries ++;
7719: sleep 1;
7720: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7721: }
7722: if ($gotlock eq 'ok') {
7723: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7724: my ($tmp)=keys(%curr_permissions);
7725: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7726: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7727: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7728: if (ref($curr_controls) eq 'HASH') {
7729: foreach my $control_item (keys(%{$curr_controls})) {
7730: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7731: if (defined($todelete{$itemnum})) {
7732: push(@deletions,$file_name."\0".$control_item);
7733: } else {
7734: if (defined($changed_items{$itemnum})) {
7735: $new_control{$changed_items{$itemnum}} = $now;
7736: push(@deletions,$file_name."\0".$control_item);
7737: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7738: } else {
7739: $new_control{$control_item} = $$curr_controls{$control_item};
7740: }
7741: }
1.745 raeburn 7742: }
7743: }
7744: }
1.970 raeburn 7745: my ($group);
7746: if (&is_course($domain,$user)) {
7747: ($group,my $file) = split(/\//,$file_name,2);
7748: }
1.749 raeburn 7749: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7750: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7751: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7752: # remove lock
7753: my @del_lock = ($file_name."\0".'locked_access_records');
7754: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7755: my $sqlresult =
1.970 raeburn 7756: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7757: $group);
1.749 raeburn 7758: } else {
7759: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7760: }
1.749 raeburn 7761: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7762: }
7763:
1.827 raeburn 7764: sub make_public_indefinitely {
7765: my ($requrl) = @_;
7766: my $now = time;
7767: my $action = 'activate';
7768: my $aclnum = 0;
7769: if (&is_portfolio_url($requrl)) {
7770: my (undef,$udom,$unum,$file_name,$group) =
7771: &parse_portfolio_url($requrl);
7772: my $current_perms = &get_portfile_permissions($udom,$unum);
7773: my %access_controls = &get_access_controls($current_perms,
7774: $group,$file_name);
7775: foreach my $key (keys(%{$access_controls{$file_name}})) {
7776: my ($num,$scope,$end,$start) =
7777: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7778: if ($scope eq 'public') {
7779: if ($start <= $now && $end == 0) {
7780: $action = 'none';
7781: } else {
7782: $action = 'update';
7783: $aclnum = $num;
7784: }
7785: last;
7786: }
7787: }
7788: if ($action eq 'none') {
7789: return 'ok';
7790: } else {
7791: my %changes;
7792: my $newend = 0;
7793: my $newstart = $now;
7794: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7795: $changes{$action}{$newkey} = {
7796: type => 'public',
7797: time => {
7798: start => $newstart,
7799: end => $newend,
7800: },
7801: };
7802: my ($outcome,$deloutcome,$new_values,$translation) =
7803: &modify_access_controls($file_name,\%changes,$udom,$unum);
7804: return $outcome;
7805: }
7806: } else {
7807: return 'invalid';
7808: }
7809: }
7810:
1.745 raeburn 7811: #------------------------------------------------------Get Marked as Read Only
7812:
7813: sub get_marked_as_readonly {
7814: my ($domain,$user,$what,$group) = @_;
7815: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7816: my @readonly_files;
1.629 banghart 7817: my $cmp1=$what;
7818: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7819: while (my ($file_name,$value) = each(%{$current_permissions})) {
7820: if (defined($group)) {
7821: if ($file_name !~ m-^\Q$group\E/-) {
7822: next;
7823: }
7824: }
1.561 banghart 7825: if (ref($value) eq "ARRAY"){
7826: foreach my $stored_what (@{$value}) {
1.629 banghart 7827: my $cmp2=$stored_what;
1.759 albertel 7828: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7829: $cmp2=join('',@{$stored_what});
1.745 raeburn 7830: }
1.629 banghart 7831: if ($cmp1 eq $cmp2) {
1.561 banghart 7832: push(@readonly_files, $file_name);
1.745 raeburn 7833: last;
1.563 banghart 7834: } elsif (!defined($what)) {
7835: push(@readonly_files, $file_name);
1.745 raeburn 7836: last;
1.561 banghart 7837: }
7838: }
1.745 raeburn 7839: }
1.561 banghart 7840: }
7841: return @readonly_files;
7842: }
1.577 banghart 7843: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7844:
1.577 banghart 7845: sub get_marked_as_readonly_hash {
1.745 raeburn 7846: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7847: my %readonly_files;
1.745 raeburn 7848: while (my ($file_name,$value) = each(%{$current_permissions})) {
7849: if (defined($group)) {
7850: if ($file_name !~ m-^\Q$group\E/-) {
7851: next;
7852: }
7853: }
1.577 banghart 7854: if (ref($value) eq "ARRAY"){
7855: foreach my $stored_what (@{$value}) {
1.745 raeburn 7856: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7857: foreach my $lock_descriptor(@{$stored_what}) {
7858: if ($lock_descriptor eq 'graded') {
7859: $readonly_files{$file_name} = 'graded';
7860: } elsif ($lock_descriptor eq 'handback') {
7861: $readonly_files{$file_name} = 'handback';
7862: } else {
7863: if (!exists($readonly_files{$file_name})) {
7864: $readonly_files{$file_name} = 'locked';
7865: }
7866: }
1.745 raeburn 7867: }
1.750 banghart 7868: }
1.577 banghart 7869: }
7870: }
7871: }
7872: return %readonly_files;
7873: }
1.559 banghart 7874: # ------------------------------------------------------------ Unmark as Read Only
7875:
7876: sub unmark_as_readonly {
1.629 banghart 7877: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7878: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7879: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7880: $file_name = &declutter_portfile($file_name);
1.634 albertel 7881: my $symb_crs = $what;
7882: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7883: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7884: my ($tmp)=keys(%current_permissions);
7885: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7886: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7887: foreach my $file (@readonly_files) {
1.759 albertel 7888: my $clean_file = &declutter_portfile($file);
7889: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7890: my $current_locks = $current_permissions{$file};
1.563 banghart 7891: my @new_locks;
7892: my @del_keys;
7893: if (ref($current_locks) eq "ARRAY"){
7894: foreach my $locker (@{$current_locks}) {
1.632 albertel 7895: my $compare=$locker;
1.749 raeburn 7896: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7897: $compare=join('',@{$locker});
1.746 raeburn 7898: if ($compare ne $symb_crs) {
7899: push(@new_locks, $locker);
7900: }
1.563 banghart 7901: }
7902: }
1.650 albertel 7903: if (scalar(@new_locks) > 0) {
1.563 banghart 7904: $current_permissions{$file} = \@new_locks;
7905: } else {
7906: push(@del_keys, $file);
1.613 albertel 7907: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7908: delete($current_permissions{$file});
1.563 banghart 7909: }
7910: }
1.561 banghart 7911: }
1.613 albertel 7912: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7913: return;
7914: }
1.512 banghart 7915:
1.17 www 7916: # ------------------------------------------------------------ Directory lister
7917:
7918: sub dirlist {
1.955 raeburn 7919: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7920: $uri=~s/^\///;
7921: $uri=~s/\/$//;
1.253 stredwic 7922: my ($udom, $uname);
1.955 raeburn 7923: if ($getuserdir) {
1.253 stredwic 7924: $udom = $userdomain;
7925: $uname = $username;
1.955 raeburn 7926: } else {
7927: (undef,$udom,$uname)=split(/\//,$uri);
7928: if(defined($userdomain)) {
7929: $udom = $userdomain;
7930: }
7931: if(defined($username)) {
7932: $uname = $username;
7933: }
1.253 stredwic 7934: }
1.955 raeburn 7935: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7936:
1.955 raeburn 7937: $dirRoot = $perlvar{'lonDocRoot'};
7938: if (defined($getpropath)) {
7939: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7940: $dirRoot =~ s/\/$//;
1.955 raeburn 7941: } elsif (defined($getuserdir)) {
7942: my $subdir=$uname.'__';
7943: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7944: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7945: ."/$udom/$subdir/$uname";
7946: } elsif (defined($alternateRoot)) {
7947: $dirRoot = $alternateRoot;
1.751 banghart 7948: }
1.253 stredwic 7949:
7950: if($udom) {
7951: if($uname) {
1.955 raeburn 7952: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7953: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7954: .':'.&escape($uname).':'.&escape($udom),
7955: &homeserver($uname,$udom));
7956: if ($listing eq 'unknown_cmd') {
7957: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7958: &homeserver($uname,$udom));
7959: } else {
7960: @listing_results = map { &unescape($_); } split(/:/,$listing);
7961: }
1.605 matthew 7962: if ($listing eq 'unknown_cmd') {
1.800 albertel 7963: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7964: &homeserver($uname,$udom));
1.605 matthew 7965: @listing_results = split(/:/,$listing);
7966: } else {
7967: @listing_results = map { &unescape($_); } split(/:/,$listing);
7968: }
7969: return @listing_results;
1.955 raeburn 7970: } elsif(!$alternateRoot) {
1.800 albertel 7971: my %allusers;
1.841 albertel 7972: my %servers = &get_servers($udom,'library');
1.955 raeburn 7973: foreach my $tryserver (keys(%servers)) {
7974: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7975: &escape($udom),$tryserver);
7976: if ($listing eq 'unknown_cmd') {
7977: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7978: $udom, $tryserver);
7979: } else {
7980: @listing_results = map { &unescape($_); } split(/:/,$listing);
7981: }
1.841 albertel 7982: if ($listing eq 'unknown_cmd') {
7983: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7984: $udom, $tryserver);
7985: @listing_results = split(/:/,$listing);
7986: } else {
7987: @listing_results =
7988: map { &unescape($_); } split(/:/,$listing);
7989: }
7990: if ($listing_results[0] ne 'no_such_dir' &&
7991: $listing_results[0] ne 'empty' &&
7992: $listing_results[0] ne 'con_lost') {
7993: foreach my $line (@listing_results) {
7994: my ($entry) = split(/&/,$line,2);
7995: $allusers{$entry} = 1;
7996: }
7997: }
1.253 stredwic 7998: }
7999: my $alluserstr='';
1.800 albertel 8000: foreach my $user (sort(keys(%allusers))) {
8001: $alluserstr.=$user.'&user:';
1.253 stredwic 8002: }
8003: $alluserstr=~s/:$//;
8004: return split(/:/,$alluserstr);
8005: } else {
1.800 albertel 8006: return ('missing user name');
1.253 stredwic 8007: }
1.955 raeburn 8008: } elsif(!defined($getpropath)) {
1.841 albertel 8009: my @all_domains = sort(&all_domains());
1.955 raeburn 8010: foreach my $domain (@all_domains) {
8011: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
8012: }
8013: return @all_domains;
8014: } else {
1.800 albertel 8015: return ('missing domain');
1.275 stredwic 8016: }
8017: }
8018:
8019: # --------------------------------------------- GetFileTimestamp
8020: # This function utilizes dirlist and returns the date stamp for
8021: # when it was last modified. It will also return an error of -1
8022: # if an error occurs
8023:
8024: sub GetFileTimestamp {
1.955 raeburn 8025: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8026: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8027: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 8028: my ($fileStat) =
8029: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
8030: undef,$getuserdir);
1.275 stredwic 8031: my @stats = split('&', $fileStat);
8032: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 8033: # @stats contains first the filename, then the stat output
8034: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8035: } else {
8036: return -1;
1.253 stredwic 8037: }
1.26 www 8038: }
8039:
1.712 albertel 8040: sub stat_file {
8041: my ($uri) = @_;
1.787 albertel 8042: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8043:
1.955 raeburn 8044: my ($udom,$uname,$file);
1.712 albertel 8045: if ($uri =~ m-^/(uploaded|editupload)/-) {
8046: ($udom,$uname,$file) =
1.811 albertel 8047: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8048: $file = 'userfiles/'.$file;
8049: }
8050: if ($uri =~ m-^/res/-) {
8051: ($udom,$uname) =
1.807 albertel 8052: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8053: $file = $uri;
8054: }
8055:
8056: if (!$udom || !$uname || !$file) {
8057: # unable to handle the uri
8058: return ();
8059: }
1.956 raeburn 8060: my $getpropath;
8061: if ($file =~ /^userfiles\//) {
8062: $getpropath = 1;
8063: }
1.955 raeburn 8064: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 8065: my @stats = split('&', $result);
1.721 banghart 8066:
1.712 albertel 8067: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8068: shift(@stats); #filename is first
8069: return @stats;
8070: }
8071: return ();
8072: }
8073:
1.26 www 8074: # -------------------------------------------------------- Value of a Condition
8075:
1.713 albertel 8076: # gets the value of a specific preevaluated condition
8077: # stored in the string $env{user.state.<cid>}
8078: # or looks up a condition reference in the bighash and if if hasn't
8079: # already been evaluated recurses into docondval to get the value of
8080: # the condition, then memoizing it to
8081: # $env{user.state.<cid>.<condition>}
1.40 www 8082: sub directcondval {
8083: my $number=shift;
1.620 albertel 8084: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8085: &Apache::lonuserstate::evalstate();
8086: }
1.713 albertel 8087: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8088: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8089: } elsif ($number =~ /^_/) {
8090: my $sub_condition;
8091: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8092: &GDBM_READER(),0640)) {
8093: $sub_condition=$bighash{'conditions'.$number};
8094: untie(%bighash);
8095: }
8096: my $value = &docondval($sub_condition);
1.949 raeburn 8097: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8098: return $value;
8099: }
1.620 albertel 8100: if ($env{'user.state.'.$env{'request.course.id'}}) {
8101: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8102: } else {
8103: return 2;
8104: }
8105: }
8106:
1.713 albertel 8107: # get the collection of conditions for this resource
1.26 www 8108: sub condval {
8109: my $condidx=shift;
1.54 www 8110: my $allpathcond='';
1.713 albertel 8111: foreach my $cond (split(/\|/,$condidx)) {
8112: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8113: $allpathcond.=
8114: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8115: }
1.191 harris41 8116: }
1.54 www 8117: $allpathcond=~s/\|$//;
1.713 albertel 8118: return &docondval($allpathcond);
8119: }
8120:
8121: #evaluates an expression of conditions
8122: sub docondval {
8123: my ($allpathcond) = @_;
8124: my $result=0;
8125: if ($env{'request.course.id'}
8126: && defined($allpathcond)) {
8127: my $operand='|';
8128: my @stack;
8129: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8130: if ($chunk eq '(') {
8131: push @stack,($operand,$result);
8132: } elsif ($chunk eq ')') {
8133: my $before=pop @stack;
8134: if (pop @stack eq '&') {
8135: $result=$result>$before?$before:$result;
8136: } else {
8137: $result=$result>$before?$result:$before;
8138: }
8139: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8140: $operand=$chunk;
8141: } else {
8142: my $new=directcondval($chunk);
8143: if ($operand eq '&') {
8144: $result=$result>$new?$new:$result;
8145: } else {
8146: $result=$result>$new?$result:$new;
8147: }
8148: }
8149: }
1.26 www 8150: }
8151: return $result;
1.421 albertel 8152: }
8153:
8154: # ---------------------------------------------------- Devalidate courseresdata
8155:
8156: sub devalidatecourseresdata {
8157: my ($coursenum,$coursedomain)=@_;
8158: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8159: &devalidate_cache_new('courseres',$hashid);
1.28 www 8160: }
8161:
1.763 www 8162:
1.200 www 8163: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8164: #
8165: # Parameters:
8166: # $coursenum - Number of the course.
8167: # $coursedomain - Domain at which the course was created.
8168: # Returns:
8169: # A hash of the course parameters along (I think) with timestamps
8170: # and version info.
1.877 foxr 8171:
1.624 albertel 8172: sub get_courseresdata {
8173: my ($coursenum,$coursedomain)=@_;
1.200 www 8174: my $coursehom=&homeserver($coursenum,$coursedomain);
8175: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8176: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8177: my %dumpreply;
1.417 albertel 8178: unless (defined($cached)) {
1.624 albertel 8179: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8180: $result=\%dumpreply;
1.251 albertel 8181: my ($tmp) = keys(%dumpreply);
8182: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8183: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8184: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8185: return $tmp;
1.416 albertel 8186: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8187: $result=undef;
1.599 albertel 8188: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8189: }
8190: }
1.624 albertel 8191: return $result;
8192: }
8193:
1.633 albertel 8194: sub devalidateuserresdata {
8195: my ($uname,$udom)=@_;
8196: my $hashid="$udom:$uname";
8197: &devalidate_cache_new('userres',$hashid);
8198: }
8199:
1.624 albertel 8200: sub get_userresdata {
8201: my ($uname,$udom)=@_;
8202: #most student don\'t have any data set, check if there is some data
8203: if (&EXT_cache_status($udom,$uname)) { return undef; }
8204:
8205: my $hashid="$udom:$uname";
8206: my ($result,$cached)=&is_cached_new('userres',$hashid);
8207: if (!defined($cached)) {
8208: my %resourcedata=&dump('resourcedata',$udom,$uname);
8209: $result=\%resourcedata;
8210: &do_cache_new('userres',$hashid,$result,600);
8211: }
8212: my ($tmp)=keys(%$result);
8213: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8214: return $result;
8215: }
8216: #error 2 occurs when the .db doesn't exist
8217: if ($tmp!~/error: 2 /) {
1.672 albertel 8218: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8219: " Trying to get resource data for ".
8220: $uname." at ".$udom.": ".
8221: $tmp."</font>");
8222: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8223: #&EXT_cache_set($udom,$uname);
8224: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8225: undef($tmp); # not really an error so don't send it back
1.624 albertel 8226: }
8227: return $tmp;
8228: }
1.879 foxr 8229: #----------------------------------------------- resdata - return resource data
8230: # Purpose:
8231: # Return resource data for either users or for a course.
8232: # Parameters:
8233: # $name - Course/user name.
8234: # $domain - Name of the domain the user/course is registered on.
8235: # $type - Type of thing $name is (must be 'course' or 'user'
8236: # @which - Array of names of resources desired.
8237: # Returns:
8238: # The value of the first reasource in @which that is found in the
8239: # resource hash.
8240: # Exceptional Conditions:
8241: # If the $type passed in is not valid (not the string 'course' or
8242: # 'user', an undefined reference is returned.
8243: # If none of the resources are found, an undef is returned
1.624 albertel 8244: sub resdata {
8245: my ($name,$domain,$type,@which)=@_;
8246: my $result;
8247: if ($type eq 'course') {
8248: $result=&get_courseresdata($name,$domain);
8249: } elsif ($type eq 'user') {
8250: $result=&get_userresdata($name,$domain);
8251: }
8252: if (!ref($result)) { return $result; }
1.251 albertel 8253: foreach my $item (@which) {
1.927 albertel 8254: if (defined($result->{$item->[0]})) {
8255: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8256: }
1.250 albertel 8257: }
1.291 albertel 8258: return undef;
1.200 www 8259: }
8260:
1.379 matthew 8261: #
8262: # EXT resource caching routines
8263: #
8264:
8265: sub clear_EXT_cache_status {
1.383 albertel 8266: &delenv('cache.EXT.');
1.379 matthew 8267: }
8268:
8269: sub EXT_cache_status {
8270: my ($target_domain,$target_user) = @_;
1.383 albertel 8271: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8272: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8273: # We know already the user has no data
8274: return 1;
8275: } else {
8276: return 0;
8277: }
8278: }
8279:
8280: sub EXT_cache_set {
8281: my ($target_domain,$target_user) = @_;
1.383 albertel 8282: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8283: #&appenv({$cachename => time});
1.379 matthew 8284: }
8285:
1.28 www 8286: # --------------------------------------------------------- Value of a Variable
1.58 www 8287: sub EXT {
1.715 albertel 8288:
1.395 albertel 8289: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8290: unless ($varname) { return ''; }
1.218 albertel 8291: #get real user name/domain, courseid and symb
8292: my $courseid;
1.359 albertel 8293: my $publicuser;
1.427 www 8294: if ($symbparm) {
8295: $symbparm=&get_symb_from_alias($symbparm);
8296: }
1.218 albertel 8297: if (!($uname && $udom)) {
1.790 albertel 8298: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8299: if (!$symbparm) { $symbparm=$cursymb; }
8300: } else {
1.620 albertel 8301: $courseid=$env{'request.course.id'};
1.218 albertel 8302: }
1.48 www 8303: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8304: my $rest;
1.320 albertel 8305: if (defined($therest[0])) {
1.48 www 8306: $rest=join('.',@therest);
8307: } else {
8308: $rest='';
8309: }
1.320 albertel 8310:
1.57 www 8311: my $qualifierrest=$qualifier;
8312: if ($rest) { $qualifierrest.='.'.$rest; }
8313: my $spacequalifierrest=$space;
8314: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8315: if ($realm eq 'user') {
1.48 www 8316: # --------------------------------------------------------------- user.resource
8317: if ($space eq 'resource') {
1.651 albertel 8318: if ( (defined($Apache::lonhomework::parsing_a_problem)
8319: || defined($Apache::lonhomework::parsing_a_task))
8320: &&
1.744 albertel 8321: ($symbparm eq &symbread()) ) {
8322: # if we are in the middle of processing the resource the
8323: # get the value we are planning on committing
8324: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8325: return $Apache::lonhomework::results{$qualifierrest};
8326: } else {
8327: return $Apache::lonhomework::history{$qualifierrest};
8328: }
1.335 albertel 8329: } else {
1.359 albertel 8330: my %restored;
1.620 albertel 8331: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8332: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8333: } else {
8334: %restored=&restore($symbparm,$courseid,$udom,$uname);
8335: }
1.335 albertel 8336: return $restored{$qualifierrest};
8337: }
1.48 www 8338: # ----------------------------------------------------------------- user.access
8339: } elsif ($space eq 'access') {
1.218 albertel 8340: # FIXME - not supporting calls for a specific user
1.48 www 8341: return &allowed($qualifier,$rest);
8342: # ------------------------------------------ user.preferences, user.environment
8343: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8344: if (($uname eq $env{'user.name'}) &&
8345: ($udom eq $env{'user.domain'})) {
8346: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8347: } else {
1.359 albertel 8348: my %returnhash;
8349: if (!$publicuser) {
8350: %returnhash=&userenvironment($udom,$uname,
8351: $qualifierrest);
8352: }
1.218 albertel 8353: return $returnhash{$qualifierrest};
8354: }
1.48 www 8355: # ----------------------------------------------------------------- user.course
8356: } elsif ($space eq 'course') {
1.218 albertel 8357: # FIXME - not supporting calls for a specific user
1.620 albertel 8358: return $env{join('.',('request.course',$qualifier))};
1.48 www 8359: # ------------------------------------------------------------------- user.role
8360: } elsif ($space eq 'role') {
1.218 albertel 8361: # FIXME - not supporting calls for a specific user
1.620 albertel 8362: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8363: if ($qualifier eq 'value') {
8364: return $role;
8365: } elsif ($qualifier eq 'extent') {
8366: return $where;
8367: }
8368: # ----------------------------------------------------------------- user.domain
8369: } elsif ($space eq 'domain') {
1.218 albertel 8370: return $udom;
1.48 www 8371: # ------------------------------------------------------------------- user.name
8372: } elsif ($space eq 'name') {
1.218 albertel 8373: return $uname;
1.48 www 8374: # ---------------------------------------------------- Any other user namespace
1.29 www 8375: } else {
1.359 albertel 8376: my %reply;
8377: if (!$publicuser) {
8378: %reply=&get($space,[$qualifierrest],$udom,$uname);
8379: }
8380: return $reply{$qualifierrest};
1.48 www 8381: }
1.236 www 8382: } elsif ($realm eq 'query') {
8383: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8384: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8385: [$spacequalifierrest]);
1.620 albertel 8386: return $env{'form.'.$spacequalifierrest};
1.236 www 8387: } elsif ($realm eq 'request') {
1.48 www 8388: # ------------------------------------------------------------- request.browser
8389: if ($space eq 'browser') {
1.430 www 8390: if ($qualifier eq 'textremote') {
1.676 albertel 8391: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8392: return 1;
8393: } else {
8394: return 0;
8395: }
8396: } else {
1.620 albertel 8397: return $env{'browser.'.$qualifier};
1.430 www 8398: }
1.57 www 8399: # ------------------------------------------------------------ request.filename
8400: } else {
1.620 albertel 8401: return $env{'request.'.$spacequalifierrest};
1.29 www 8402: }
1.28 www 8403: } elsif ($realm eq 'course') {
1.48 www 8404: # ---------------------------------------------------------- course.description
1.620 albertel 8405: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8406: } elsif ($realm eq 'resource') {
1.165 www 8407:
1.620 albertel 8408: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8409: if (!$symbparm) { $symbparm=&symbread(); }
8410: }
1.693 albertel 8411:
8412: if ($space eq 'title') {
8413: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8414: return &gettitle($symbparm);
8415: }
8416:
8417: if ($space eq 'map') {
8418: my ($map) = &decode_symb($symbparm);
8419: return &symbread($map);
8420: }
1.905 albertel 8421: if ($space eq 'filename') {
8422: if ($symbparm) {
8423: return &clutter((&decode_symb($symbparm))[2]);
8424: }
8425: return &hreflocation('',$env{'request.filename'});
8426: }
1.693 albertel 8427:
8428: my ($section, $group, @groups);
1.593 albertel 8429: my ($courselevelm,$courselevel);
1.539 albertel 8430: if ($symbparm && defined($courseid) &&
1.620 albertel 8431: $courseid eq $env{'request.course.id'}) {
1.165 www 8432:
1.218 albertel 8433: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8434:
1.60 www 8435: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8436: my $symbp=$symbparm;
1.735 albertel 8437: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8438:
8439: my $symbparm=$symbp.'.'.$spacequalifierrest;
8440: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8441:
1.620 albertel 8442: if (($env{'user.name'} eq $uname) &&
8443: ($env{'user.domain'} eq $udom)) {
8444: $section=$env{'request.course.sec'};
1.733 raeburn 8445: @groups = split(/:/,$env{'request.course.groups'});
8446: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8447: } else {
1.539 albertel 8448: if (! defined($usection)) {
1.551 albertel 8449: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8450: } else {
8451: $section = $usection;
8452: }
1.733 raeburn 8453: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8454: }
8455:
8456: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8457: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8458: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8459:
1.593 albertel 8460: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8461: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8462: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8463:
1.60 www 8464: # ----------------------------------------------------------- first, check user
1.624 albertel 8465:
8466: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8467: ([$courselevelr,'resource'],
8468: [$courselevelm,'map' ],
8469: [$courselevel, 'course' ]));
1.931 albertel 8470: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8471:
1.594 albertel 8472: # ------------------------------------------------ second, check some of course
1.684 raeburn 8473: my $coursereply;
1.691 raeburn 8474: if (@groups > 0) {
8475: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8476: $mapparm,$spacequalifierrest);
1.927 albertel 8477: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8478: }
1.96 www 8479:
1.684 raeburn 8480: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8481: $env{'course.'.$courseid.'.domain'},
8482: 'course',
8483: ([$seclevelr, 'resource'],
8484: [$seclevelm, 'map' ],
8485: [$seclevel, 'course' ],
8486: [$courselevelr,'resource']));
8487: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8488:
1.60 www 8489: # ------------------------------------------------------ third, check map parms
1.218 albertel 8490: my %parmhash=();
8491: my $thisparm='';
8492: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8493: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8494: &GDBM_READER(),0640)) {
1.218 albertel 8495: $thisparm=$parmhash{$symbparm};
8496: untie(%parmhash);
8497: }
1.927 albertel 8498: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8499: }
1.594 albertel 8500: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8501:
1.218 albertel 8502: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8503: my $filename;
8504: if (!$symbparm) { $symbparm=&symbread(); }
8505: if ($symbparm) {
1.409 www 8506: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8507: } else {
1.620 albertel 8508: $filename=$env{'request.filename'};
1.282 albertel 8509: }
8510: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8511: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8512: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8513: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8514:
1.927 albertel 8515: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8516: if ($symbparm && defined($courseid) &&
1.620 albertel 8517: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8518: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8519: $env{'course.'.$courseid.'.domain'},
8520: 'course',
1.927 albertel 8521: ([$courselevelm,'map' ],
8522: [$courselevel, 'course']));
8523: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8524: }
1.145 www 8525: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8526: unless ($space eq '0') {
1.336 albertel 8527: my @parts=split(/_/,$space);
8528: my $id=pop(@parts);
8529: my $part=join('_',@parts);
8530: if ($part eq '') { $part='0'; }
1.927 albertel 8531: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8532: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8533: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8534: }
1.395 albertel 8535: if ($recurse) { return undef; }
8536: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8537: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8538: # ---------------------------------------------------- Any other user namespace
8539: } elsif ($realm eq 'environment') {
8540: # ----------------------------------------------------------------- environment
1.620 albertel 8541: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8542: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8543: } else {
1.770 albertel 8544: if ($uname eq 'anonymous' && $udom eq '') {
8545: return '';
8546: }
1.219 albertel 8547: my %returnhash=&userenvironment($udom,$uname,
8548: $spacequalifierrest);
8549: return $returnhash{$spacequalifierrest};
8550: }
1.28 www 8551: } elsif ($realm eq 'system') {
1.48 www 8552: # ----------------------------------------------------------------- system.time
8553: if ($space eq 'time') {
8554: return time;
8555: }
1.696 albertel 8556: } elsif ($realm eq 'server') {
8557: # ----------------------------------------------------------------- system.time
8558: if ($space eq 'name') {
8559: return $ENV{'SERVER_NAME'};
8560: }
1.28 www 8561: }
1.48 www 8562: return '';
1.61 www 8563: }
8564:
1.927 albertel 8565: sub get_reply {
8566: my ($reply_value) = @_;
1.940 raeburn 8567: if (ref($reply_value) eq 'ARRAY') {
8568: if (wantarray) {
8569: return @$reply_value;
8570: }
8571: return $reply_value->[0];
8572: } else {
8573: return $reply_value;
1.927 albertel 8574: }
8575: }
8576:
1.691 raeburn 8577: sub check_group_parms {
8578: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8579: my @groupitems = ();
8580: my $resultitem;
1.927 albertel 8581: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8582: foreach my $group (@{$groups}) {
8583: foreach my $level (@levels) {
1.927 albertel 8584: my $item = $courseid.'.['.$group.'].'.$level->[0];
8585: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8586: }
8587: }
8588: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8589: $env{'course.'.$courseid.'.domain'},
8590: 'course',@groupitems);
8591: return $coursereply;
8592: }
8593:
8594: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8595: my ($courseid,@groups) = @_;
8596: @groups = sort(@groups);
1.691 raeburn 8597: return @groups;
8598: }
8599:
1.395 albertel 8600: sub packages_tab_default {
8601: my ($uri,$varname)=@_;
8602: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8603:
8604: my (@extension,@specifics,$do_default);
8605: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8606: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8607: if ($pack_type eq 'default') {
8608: $do_default=1;
8609: } elsif ($pack_type eq 'extension') {
8610: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8611: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8612: # only look at packages defaults for packages that this id is
1.738 albertel 8613: push(@specifics,[$package,$pack_type,$pack_part]);
8614: }
8615: }
8616: # first look for a package that matches the requested part id
8617: foreach my $package (@specifics) {
8618: my (undef,$pack_type,$pack_part)=@{$package};
8619: next if ($pack_part ne $part);
8620: if (defined($packagetab{"$pack_type&$name&default"})) {
8621: return $packagetab{"$pack_type&$name&default"};
8622: }
8623: }
8624: # look for any possible matching non extension_ package
8625: foreach my $package (@specifics) {
8626: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8627: if (defined($packagetab{"$pack_type&$name&default"})) {
8628: return $packagetab{"$pack_type&$name&default"};
8629: }
1.585 albertel 8630: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8631: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8632: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8633: }
8634: }
1.738 albertel 8635: # look for any posible extension_ match
8636: foreach my $package (@extension) {
8637: my ($package,$pack_type)=@{$package};
8638: if (defined($packagetab{"$pack_type&$name&default"})) {
8639: return $packagetab{"$pack_type&$name&default"};
8640: }
8641: if (defined($packagetab{$package."&$name&default"})) {
8642: return $packagetab{$package."&$name&default"};
8643: }
8644: }
8645: # look for a global default setting
8646: if ($do_default && defined($packagetab{"default&$name&default"})) {
8647: return $packagetab{"default&$name&default"};
8648: }
1.395 albertel 8649: return undef;
8650: }
8651:
1.334 albertel 8652: sub add_prefix_and_part {
8653: my ($prefix,$part)=@_;
8654: my $keyroot;
8655: if (defined($prefix) && $prefix !~ /^__/) {
8656: # prefix that has a part already
8657: $keyroot=$prefix;
8658: } elsif (defined($prefix)) {
8659: # prefix that is missing a part
8660: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8661: } else {
8662: # no prefix at all
8663: if (defined($part)) { $keyroot='_'.$part; }
8664: }
8665: return $keyroot;
8666: }
8667:
1.71 www 8668: # ---------------------------------------------------------------- Get metadata
8669:
1.599 albertel 8670: my %metaentry;
1.1070 www 8671: my %importedpartids;
1.71 www 8672: sub metadata {
1.176 www 8673: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8674: $uri=&declutter($uri);
1.288 albertel 8675: # if it is a non metadata possible uri return quickly
1.529 albertel 8676: if (($uri eq '') ||
8677: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8678: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 8679: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8680: return undef;
8681: }
8682: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8683: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8684: return undef;
1.288 albertel 8685: }
1.73 www 8686: my $filename=$uri;
8687: $uri=~s/\.meta$//;
1.172 www 8688: #
8689: # Is the metadata already cached?
1.177 www 8690: # Look at timestamp of caching
1.172 www 8691: # Everything is cached by the main uri, libraries are never directly cached
8692: #
1.428 albertel 8693: if (!defined($liburi)) {
1.599 albertel 8694: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8695: if (defined($cached)) { return $result->{':'.$what}; }
8696: }
8697: {
1.1069 www 8698: # Imported parts would go here
1.1070 www 8699: my %importedids=();
8700: my @origfileimportpartids=();
1.1069 www 8701: my $importedparts=0;
1.172 www 8702: #
8703: # Is this a recursive call for a library?
8704: #
1.599 albertel 8705: # if (! exists($metacache{$uri})) {
8706: # $metacache{$uri}={};
8707: # }
1.924 albertel 8708: my $cachetime = 60*60;
1.171 www 8709: if ($liburi) {
8710: $liburi=&declutter($liburi);
8711: $filename=$liburi;
1.401 bowersj2 8712: } else {
1.599 albertel 8713: &devalidate_cache_new('meta',$uri);
8714: undef(%metaentry);
1.401 bowersj2 8715: }
1.140 www 8716: my %metathesekeys=();
1.73 www 8717: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8718: my $metastring;
1.924 albertel 8719: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8720: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8721: $metastring =
1.929 albertel 8722: &Apache::lonnet::ssi_body($which,
1.924 albertel 8723: ('grade_target' => 'meta'));
8724: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 8725: } elsif (($uri !~ m -^(editupload)/-) &&
8726: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 8727: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8728: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8729: $metastring=&getfile($file);
1.489 albertel 8730: }
1.208 albertel 8731: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8732: my $token;
1.140 www 8733: undef %metathesekeys;
1.71 www 8734: while ($token=$parser->get_token) {
1.339 albertel 8735: if ($token->[0] eq 'S') {
8736: if (defined($token->[2]->{'package'})) {
1.172 www 8737: #
8738: # This is a package - get package info
8739: #
1.339 albertel 8740: my $package=$token->[2]->{'package'};
8741: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8742: if (defined($token->[2]->{'id'})) {
8743: $keyroot.='_'.$token->[2]->{'id'};
8744: }
1.599 albertel 8745: if ($metaentry{':packages'}) {
8746: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8747: } else {
1.599 albertel 8748: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8749: }
1.736 albertel 8750: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8751: my $part=$keyroot;
8752: $part=~s/^\_//;
1.736 albertel 8753: if ($pack_entry=~/^\Q$package\E\&/ ||
8754: $pack_entry=~/^\Q$package\E_0\&/) {
8755: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8756: # ignore package.tab specified default values
8757: # here &package_tab_default() will fetch those
8758: if ($subp eq 'default') { next; }
1.736 albertel 8759: my $value=$packagetab{$pack_entry};
1.432 albertel 8760: my $unikey;
8761: if ($pack =~ /_0$/) {
8762: $unikey='parameter_0_'.$name;
8763: $part=0;
8764: } else {
8765: $unikey='parameter'.$keyroot.'_'.$name;
8766: }
1.339 albertel 8767: if ($subp eq 'display') {
8768: $value.=' [Part: '.$part.']';
8769: }
1.599 albertel 8770: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8771: $metathesekeys{$unikey}=1;
1.599 albertel 8772: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8773: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8774: }
1.599 albertel 8775: if (defined($metaentry{':'.$unikey.'.default'})) {
8776: $metaentry{':'.$unikey}=
8777: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8778: }
1.339 albertel 8779: }
8780: }
8781: } else {
1.172 www 8782: #
8783: # This is not a package - some other kind of start tag
1.339 albertel 8784: #
8785: my $entry=$token->[1];
1.1068 www 8786: my $unikey='';
1.175 www 8787:
1.339 albertel 8788: if ($entry eq 'import') {
1.175 www 8789: #
8790: # Importing a library here
1.339 albertel 8791: #
1.1067 www 8792: my $location=$parser->get_text('/import');
8793: my $dir=$filename;
8794: $dir=~s|[^/]*$||;
8795: $location=&filelocation($dir,$location);
1.1069 www 8796:
1.1068 www 8797: my $importmode=$token->[2]->{'importmode'};
8798: if ($importmode eq 'problem') {
1.1069 www 8799: # Import as problem/response
1.1068 www 8800: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8801: } elsif ($importmode eq 'part') {
8802: # Import as part(s)
1.1069 www 8803: $importedparts=1;
8804: # We need to get the original file and the imported file to get the part order correct
8805: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8806: # Load and inspect original file
1.1070 www 8807: if ($#origfileimportpartids<0) {
8808: undef(%importedpartids);
8809: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8810: my $origfile=&getfile($origfilelocation);
8811: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8812: }
8813:
1.1069 www 8814: # Load and inspect imported file
8815: my $impfile=&getfile($location);
8816: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8817: if ($#impfilepartids>=0) {
8818: # This problem had parts
1.1070 www 8819: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8820: } else {
8821: # Importing by turning a single problem into a problem part
8822: # It gets the import-tags ID as part-ID
8823: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8824: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8825: }
1.1068 www 8826: } else {
8827: # Normal import
8828: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8829: if (defined($token->[2]->{'id'})) {
8830: $unikey.='_'.$token->[2]->{'id'};
8831: }
1.1067 www 8832: }
8833:
1.339 albertel 8834: if ($depthcount<20) {
1.736 albertel 8835: my $metadata =
8836: &metadata($uri,'keys', $location,$unikey,
8837: $depthcount+1);
8838: foreach my $meta (split(',',$metadata)) {
8839: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8840: $metathesekeys{$meta}=1;
1.339 albertel 8841: }
1.1068 www 8842:
8843: }
1.1067 www 8844: } else {
8845: #
8846: # Not importing, some other kind of non-package, non-library start tag
8847: #
8848: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8849: if (defined($token->[2]->{'id'})) {
8850: $unikey.='_'.$token->[2]->{'id'};
8851: }
1.339 albertel 8852: if (defined($token->[2]->{'name'})) {
8853: $unikey.='_'.$token->[2]->{'name'};
8854: }
8855: $metathesekeys{$unikey}=1;
1.736 albertel 8856: foreach my $param (@{$token->[3]}) {
8857: $metaentry{':'.$unikey.'.'.$param} =
8858: $token->[2]->{$param};
1.339 albertel 8859: }
8860: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8861: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8862: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8863: # only ws inside the tag, and not in default, so use default
8864: # as value
1.599 albertel 8865: $metaentry{':'.$unikey}=$default;
1.908 albertel 8866: } elsif ( $internaltext =~ /\S/ ) {
8867: # something interesting inside the tag
8868: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8869: } else {
1.908 albertel 8870: # no interesting values, don't set a default
1.339 albertel 8871: }
1.172 www 8872: # end of not-a-package not-a-library import
1.339 albertel 8873: }
1.172 www 8874: # end of not-a-package start tag
1.339 albertel 8875: }
1.172 www 8876: # the next is the end of "start tag"
1.339 albertel 8877: }
8878: }
1.483 albertel 8879: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8880: $extension = lc($extension);
8881: if ($extension eq 'htm') { $extension='html'; }
8882:
1.737 albertel 8883: foreach my $key (keys(%packagetab)) {
1.483 albertel 8884: #no specific packages #how's our extension
8885: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8886: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8887: \%metathesekeys);
8888: }
1.883 albertel 8889:
8890: if (!exists($metaentry{':packages'})
8891: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8892: foreach my $key (keys(%packagetab)) {
1.483 albertel 8893: #no specific packages well let's get default then
8894: if ($key!~/^default&/) { next; }
1.488 albertel 8895: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8896: \%metathesekeys);
8897: }
8898: }
1.338 www 8899: # are there custom rights to evaluate
1.599 albertel 8900: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8901:
1.338 www 8902: #
8903: # Importing a rights file here
1.339 albertel 8904: #
8905: unless ($depthcount) {
1.599 albertel 8906: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8907: my $dir=$filename;
8908: $dir=~s|[^/]*$||;
8909: $location=&filelocation($dir,$location);
1.736 albertel 8910: my $rights_metadata =
8911: &metadata($uri,'keys',$location,'_rights',
8912: $depthcount+1);
8913: foreach my $rights (split(',',$rights_metadata)) {
8914: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8915: $metathesekeys{$rights}=1;
1.339 albertel 8916: }
8917: }
8918: }
1.737 albertel 8919: # uniqifiy package listing
8920: my %seen;
8921: my @uniq_packages =
8922: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8923: $metaentry{':packages'} = join(',',@uniq_packages);
8924:
1.1070 www 8925: if ($importedparts) {
8926: # We had imported parts and need to rebuild partorder
8927: $metaentry{':partorder'}='';
8928: $metathesekeys{'partorder'}=1;
8929: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8930: if ($origfileimportpartids[$index] eq 'part') {
8931: # original part, part of the problem
8932: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8933: } else {
8934: # we have imported parts at this position
8935: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8936: }
8937: }
8938: $metaentry{':partorder'}=~s/^\,//;
8939: }
8940:
1.737 albertel 8941: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8942: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8943: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8944: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8945: # this is the end of "was not already recently cached
1.71 www 8946: }
1.599 albertel 8947: return $metaentry{':'.$what};
1.261 albertel 8948: }
8949:
1.488 albertel 8950: sub metadata_create_package_def {
1.483 albertel 8951: my ($uri,$key,$package,$metathesekeys)=@_;
8952: my ($pack,$name,$subp)=split(/\&/,$key);
8953: if ($subp eq 'default') { next; }
8954:
1.599 albertel 8955: if (defined($metaentry{':packages'})) {
8956: $metaentry{':packages'}.=','.$package;
1.483 albertel 8957: } else {
1.599 albertel 8958: $metaentry{':packages'}=$package;
1.483 albertel 8959: }
8960: my $value=$packagetab{$key};
8961: my $unikey;
8962: $unikey='parameter_0_'.$name;
1.599 albertel 8963: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8964: $$metathesekeys{$unikey}=1;
1.599 albertel 8965: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8966: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8967: }
1.599 albertel 8968: if (defined($metaentry{':'.$unikey.'.default'})) {
8969: $metaentry{':'.$unikey}=
8970: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8971: }
8972: }
8973:
1.261 albertel 8974: sub metadata_generate_part0 {
8975: my ($metadata,$metacache,$uri) = @_;
8976: my %allnames;
1.737 albertel 8977: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8978: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8979: my $part=$$metacache{':'.$metakey.'.part'};
8980: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8981: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8982: $allnames{$name}=$part;
8983: }
8984: }
8985: }
8986: foreach my $name (keys(%allnames)) {
8987: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8988: my $key=":parameter_0_$name";
1.261 albertel 8989: $$metacache{"$key.part"}='0';
8990: $$metacache{"$key.name"}=$name;
1.428 albertel 8991: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8992: $allnames{$name}.'_'.$name.
8993: '.type'};
1.428 albertel 8994: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8995: '.display'};
1.644 www 8996: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8997: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8998: $$metacache{"$key.display"}=$olddis;
8999: }
1.71 www 9000: }
9001:
1.764 albertel 9002: # ------------------------------------------------------ Devalidate title cache
9003:
9004: sub devalidate_title_cache {
9005: my ($url)=@_;
9006: if (!$env{'request.course.id'}) { return; }
9007: my $symb=&symbread($url);
9008: if (!$symb) { return; }
9009: my $key=$env{'request.course.id'}."\0".$symb;
9010: &devalidate_cache_new('title',$key);
9011: }
9012:
1.1014 droeschl 9013: # ------------------------------------------------- Get the title of a course
9014:
9015: sub current_course_title {
9016: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9017: }
1.301 www 9018: # ------------------------------------------------- Get the title of a resource
9019:
9020: sub gettitle {
9021: my $urlsymb=shift;
9022: my $symb=&symbread($urlsymb);
1.534 albertel 9023: if ($symb) {
1.620 albertel 9024: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9025: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9026: if (defined($cached)) {
9027: return $result;
9028: }
1.534 albertel 9029: my ($map,$resid,$url)=&decode_symb($symb);
9030: my $title='';
1.907 albertel 9031: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9032: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9033: } else {
9034: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9035: &GDBM_READER(),0640)) {
9036: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9037: $title=$bighash{'title_'.$mapid.'.'.$resid};
9038: untie(%bighash);
9039: }
1.534 albertel 9040: }
9041: $title=~s/\&colon\;/\:/gs;
9042: if ($title) {
1.599 albertel 9043: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9044: }
9045: $urlsymb=$url;
9046: }
9047: my $title=&metadata($urlsymb,'title');
9048: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9049: return $title;
1.301 www 9050: }
1.613 albertel 9051:
1.614 albertel 9052: sub get_slot {
9053: my ($which,$cnum,$cdom)=@_;
9054: if (!$cnum || !$cdom) {
1.790 albertel 9055: (undef,my $courseid)=&whichuser();
1.620 albertel 9056: $cdom=$env{'course.'.$courseid.'.domain'};
9057: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9058: }
1.703 albertel 9059: my $key=join("\0",'slots',$cdom,$cnum,$which);
9060: my %slotinfo;
9061: if (exists($remembered{$key})) {
9062: $slotinfo{$which} = $remembered{$key};
9063: } else {
9064: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9065: &Apache::lonhomework::showhash(%slotinfo);
9066: my ($tmp)=keys(%slotinfo);
9067: if ($tmp=~/^error:/) { return (); }
9068: $remembered{$key} = $slotinfo{$which};
9069: }
1.616 albertel 9070: if (ref($slotinfo{$which}) eq 'HASH') {
9071: return %{$slotinfo{$which}};
9072: }
9073: return $slotinfo{$which};
1.614 albertel 9074: }
1.31 www 9075: # ------------------------------------------------- Update symbolic store links
9076:
9077: sub symblist {
9078: my ($mapname,%newhash)=@_;
1.438 www 9079: $mapname=&deversion(&declutter($mapname));
1.31 www 9080: my %hash;
1.620 albertel 9081: if (($env{'request.course.fn'}) && (%newhash)) {
9082: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9083: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9084: foreach my $url (keys(%newhash)) {
1.711 albertel 9085: next if ($url eq 'last_known'
9086: && $env{'form.no_update_last_known'});
9087: $hash{declutter($url)}=&encode_symb($mapname,
9088: $newhash{$url}->[1],
9089: $newhash{$url}->[0]);
1.191 harris41 9090: }
1.31 www 9091: if (untie(%hash)) {
9092: return 'ok';
9093: }
9094: }
9095: }
9096: return 'error';
1.212 www 9097: }
9098:
9099: # --------------------------------------------------------------- Verify a symb
9100:
9101: sub symbverify {
1.510 www 9102: my ($symb,$thisurl)=@_;
9103: my $thisfn=$thisurl;
1.439 www 9104: $thisfn=&declutter($thisfn);
1.215 www 9105: # direct jump to resource in page or to a sequence - will construct own symbs
9106: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9107: # check URL part
1.409 www 9108: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9109:
1.431 www 9110: unless ($url eq $thisfn) { return 0; }
1.213 www 9111:
1.216 www 9112: $symb=&symbclean($symb);
1.510 www 9113: $thisurl=&deversion($thisurl);
1.439 www 9114: $thisfn=&deversion($thisfn);
1.213 www 9115:
9116: my %bighash;
9117: my $okay=0;
1.431 www 9118:
1.620 albertel 9119: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9120: &GDBM_READER(),0640)) {
1.1032 raeburn 9121: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9122: $thisurl =~ s/\?.+$//;
9123: }
1.510 www 9124: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9125: unless ($ids) {
9126: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9127: $ids=$bighash{$idkey};
1.216 www 9128: }
9129: if ($ids) {
9130: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9131: foreach my $id (split(/\,/,$ids)) {
9132: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9133: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9134: $symb =~ s/\?.+$//;
9135: }
1.216 www 9136: if (
9137: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9138: eq $symb) {
1.620 albertel 9139: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9140: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9141: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9142: $okay=1;
9143: }
9144: }
1.216 www 9145: }
9146: }
1.213 www 9147: untie(%bighash);
9148: }
9149: return $okay;
1.31 www 9150: }
9151:
1.210 www 9152: # --------------------------------------------------------------- Clean-up symb
9153:
9154: sub symbclean {
9155: my $symb=shift;
1.568 albertel 9156: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9157: # remove version from map
9158: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9159:
1.210 www 9160: # remove version from URL
9161: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9162:
1.507 www 9163: # remove wrapper
9164:
1.510 www 9165: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9166: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9167: return $symb;
1.409 www 9168: }
9169:
9170: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9171:
9172: sub encode_symb {
9173: my ($map,$resid,$url)=@_;
9174: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9175: }
1.409 www 9176:
9177: sub decode_symb {
1.568 albertel 9178: my $symb=shift;
9179: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9180: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9181: return (&fixversion($map),$resid,&fixversion($url));
9182: }
9183:
9184: sub fixversion {
9185: my $fn=shift;
1.609 banghart 9186: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9187: my %bighash;
9188: my $uri=&clutter($fn);
1.620 albertel 9189: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9190: # is this cached?
1.599 albertel 9191: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9192: if (defined($cached)) { return $result; }
9193: # unfortunately not cached, or expired
1.620 albertel 9194: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9195: &GDBM_READER(),0640)) {
9196: if ($bighash{'version_'.$uri}) {
9197: my $version=$bighash{'version_'.$uri};
1.444 www 9198: unless (($version eq 'mostrecent') ||
9199: ($version==&getversion($uri))) {
1.440 www 9200: $uri=~s/\.(\w+)$/\.$version\.$1/;
9201: }
9202: }
9203: untie %bighash;
1.413 www 9204: }
1.599 albertel 9205: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9206: }
9207:
9208: sub deversion {
9209: my $url=shift;
9210: $url=~s/\.\d+\.(\w+)$/\.$1/;
9211: return $url;
1.210 www 9212: }
9213:
1.31 www 9214: # ------------------------------------------------------ Return symb list entry
9215:
9216: sub symbread {
1.249 www 9217: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9218: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9219: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9220: # no filename provided? try from environment
1.44 www 9221: unless ($thisfn) {
1.620 albertel 9222: if ($env{'request.symb'}) {
9223: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9224: }
1.620 albertel 9225: $thisfn=$env{'request.filename'};
1.44 www 9226: }
1.569 albertel 9227: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9228: # is that filename actually a symb? Verify, clean, and return
9229: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9230: if (&symbverify($thisfn,$1)) {
1.620 albertel 9231: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9232: }
1.242 www 9233: }
1.44 www 9234: $thisfn=declutter($thisfn);
1.31 www 9235: my %hash;
1.37 www 9236: my %bighash;
9237: my $syval='';
1.620 albertel 9238: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9239: my $targetfn = $thisfn;
1.609 banghart 9240: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9241: $targetfn = 'adm/wrapper/'.$thisfn;
9242: }
1.687 albertel 9243: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9244: $targetfn=$1;
9245: }
1.620 albertel 9246: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9247: &GDBM_READER(),0640)) {
1.481 raeburn 9248: $syval=$hash{$targetfn};
1.37 www 9249: untie(%hash);
9250: }
9251: # ---------------------------------------------------------- There was an entry
9252: if ($syval) {
1.601 albertel 9253: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9254: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9255: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9256: #return $env{$cache_str}='';
1.601 albertel 9257: #}
9258: #$syval.=$1;
9259: #}
1.37 www 9260: } else {
9261: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9262: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9263: &GDBM_READER(),0640)) {
1.37 www 9264: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9265: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9266: unless ($ids) {
9267: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9268: }
9269: unless ($ids) {
9270: # alias?
9271: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9272: }
1.37 www 9273: if ($ids) {
9274: # ------------------------------------------------------------------- Has ID(s)
9275: my @possibilities=split(/\,/,$ids);
1.39 www 9276: if ($#possibilities==0) {
9277: # ----------------------------------------------- There is only one possibility
1.37 www 9278: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9279: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9280: $resid,$thisfn);
1.249 www 9281: } elsif (!$donotrecurse) {
1.39 www 9282: # ------------------------------------------ There is more than one possibility
9283: my $realpossible=0;
1.800 albertel 9284: foreach my $id (@possibilities) {
9285: my $file=$bighash{'src_'.$id};
1.39 www 9286: if (&allowed('bre',$file)) {
1.800 albertel 9287: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9288: if ($bighash{'map_type_'.$mapid} ne 'page') {
9289: $realpossible++;
1.626 albertel 9290: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9291: $resid,$thisfn);
1.39 www 9292: }
9293: }
1.191 harris41 9294: }
1.39 www 9295: if ($realpossible!=1) { $syval=''; }
1.249 www 9296: } else {
9297: $syval='';
1.37 www 9298: }
9299: }
9300: untie(%bighash)
1.481 raeburn 9301: }
1.31 www 9302: }
1.62 www 9303: if ($syval) {
1.620 albertel 9304: return $env{$cache_str}=$syval;
1.62 www 9305: }
1.31 www 9306: }
1.949 raeburn 9307: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9308: return $env{$cache_str}='';
1.31 www 9309: }
9310:
9311: # ---------------------------------------------------------- Return random seed
9312:
1.32 www 9313: sub numval {
9314: my $txt=shift;
9315: $txt=~tr/A-J/0-9/;
9316: $txt=~tr/a-j/0-9/;
9317: $txt=~tr/K-T/0-9/;
9318: $txt=~tr/k-t/0-9/;
9319: $txt=~tr/U-Z/0-5/;
9320: $txt=~tr/u-z/0-5/;
9321: $txt=~s/\D//g;
1.564 albertel 9322: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9323: return int($txt);
1.368 albertel 9324: }
9325:
1.484 albertel 9326: sub numval2 {
9327: my $txt=shift;
9328: $txt=~tr/A-J/0-9/;
9329: $txt=~tr/a-j/0-9/;
9330: $txt=~tr/K-T/0-9/;
9331: $txt=~tr/k-t/0-9/;
9332: $txt=~tr/U-Z/0-5/;
9333: $txt=~tr/u-z/0-5/;
9334: $txt=~s/\D//g;
9335: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9336: my $total;
9337: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9338: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9339: return int($total);
9340: }
9341:
1.575 albertel 9342: sub numval3 {
9343: use integer;
9344: my $txt=shift;
9345: $txt=~tr/A-J/0-9/;
9346: $txt=~tr/a-j/0-9/;
9347: $txt=~tr/K-T/0-9/;
9348: $txt=~tr/k-t/0-9/;
9349: $txt=~tr/U-Z/0-5/;
9350: $txt=~tr/u-z/0-5/;
9351: $txt=~s/\D//g;
9352: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9353: my $total;
9354: foreach my $val (@txts) { $total+=$val; }
9355: if ($_64bit) { $total=(($total<<32)>>32); }
9356: return $total;
9357: }
9358:
1.675 albertel 9359: sub digest {
9360: my ($data)=@_;
9361: my $digest=&Digest::MD5::md5($data);
9362: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9363: my ($e,$f);
9364: {
9365: use integer;
9366: $e=($a+$b);
9367: $f=($c+$d);
9368: if ($_64bit) {
9369: $e=(($e<<32)>>32);
9370: $f=(($f<<32)>>32);
9371: }
9372: }
9373: if (wantarray) {
9374: return ($e,$f);
9375: } else {
9376: my $g;
9377: {
9378: use integer;
9379: $g=($e+$f);
9380: if ($_64bit) {
9381: $g=(($g<<32)>>32);
9382: }
9383: }
9384: return $g;
9385: }
9386: }
9387:
1.368 albertel 9388: sub latest_rnd_algorithm_id {
1.675 albertel 9389: return '64bit5';
1.366 albertel 9390: }
1.32 www 9391:
1.503 albertel 9392: sub get_rand_alg {
9393: my ($courseid)=@_;
1.790 albertel 9394: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9395: if ($courseid) {
1.620 albertel 9396: return $env{"course.$courseid.rndseed"};
1.503 albertel 9397: }
9398: return &latest_rnd_algorithm_id();
9399: }
9400:
1.562 albertel 9401: sub validCODE {
9402: my ($CODE)=@_;
9403: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9404: return 0;
9405: }
9406:
1.491 albertel 9407: sub getCODE {
1.620 albertel 9408: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9409: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9410: defined($Apache::lonhomework::parsing_a_task) ) &&
9411: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9412: return $Apache::lonhomework::history{'resource.CODE'};
9413: }
9414: return undef;
9415: }
9416:
1.31 www 9417: sub rndseed {
1.155 albertel 9418: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9419: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9420: if (!defined($symb)) {
1.366 albertel 9421: unless ($symb=$wsymb) { return time; }
9422: }
9423: if (!$courseid) { $courseid=$wcourseid; }
9424: if (!$domain) { $domain=$wdomain; }
9425: if (!$username) { $username=$wusername }
1.503 albertel 9426: my $which=&get_rand_alg();
1.1110 www 9427:
1.491 albertel 9428: if (defined(&getCODE())) {
1.675 albertel 9429: if ($which eq '64bit5') {
9430: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9431: } elsif ($which eq '64bit4') {
1.575 albertel 9432: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9433: } else {
9434: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9435: }
1.675 albertel 9436: } elsif ($which eq '64bit5') {
9437: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9438: } elsif ($which eq '64bit4') {
9439: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9440: } elsif ($which eq '64bit3') {
9441: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9442: } elsif ($which eq '64bit2') {
9443: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9444: } elsif ($which eq '64bit') {
9445: return &rndseed_64bit($symb,$courseid,$domain,$username);
9446: }
9447: return &rndseed_32bit($symb,$courseid,$domain,$username);
9448: }
9449:
9450: sub rndseed_32bit {
9451: my ($symb,$courseid,$domain,$username)=@_;
9452: {
9453: use integer;
9454: my $symbchck=unpack("%32C*",$symb) << 27;
9455: my $symbseed=numval($symb) << 22;
9456: my $namechck=unpack("%32C*",$username) << 17;
9457: my $nameseed=numval($username) << 12;
9458: my $domainseed=unpack("%32C*",$domain) << 7;
9459: my $courseseed=unpack("%32C*",$courseid);
9460: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9461: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9462: #&logthis("rndseed :$num:$symb");
1.564 albertel 9463: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9464: return $num;
9465: }
9466: }
9467:
9468: sub rndseed_64bit {
9469: my ($symb,$courseid,$domain,$username)=@_;
9470: {
9471: use integer;
9472: my $symbchck=unpack("%32S*",$symb) << 21;
9473: my $symbseed=numval($symb) << 10;
9474: my $namechck=unpack("%32S*",$username);
9475:
9476: my $nameseed=numval($username) << 21;
9477: my $domainseed=unpack("%32S*",$domain) << 10;
9478: my $courseseed=unpack("%32S*",$courseid);
9479:
9480: my $num1=$symbchck+$symbseed+$namechck;
9481: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9482: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9483: #&logthis("rndseed :$num:$symb");
1.564 albertel 9484: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9485: return "$num1,$num2";
1.155 albertel 9486: }
1.366 albertel 9487: }
9488:
1.443 albertel 9489: sub rndseed_64bit2 {
9490: my ($symb,$courseid,$domain,$username)=@_;
9491: {
9492: use integer;
9493: # strings need to be an even # of cahracters long, it it is odd the
9494: # last characters gets thrown away
9495: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9496: my $symbseed=numval($symb) << 10;
9497: my $namechck=unpack("%32S*",$username.' ');
9498:
9499: my $nameseed=numval($username) << 21;
1.501 albertel 9500: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9501: my $courseseed=unpack("%32S*",$courseid.' ');
9502:
9503: my $num1=$symbchck+$symbseed+$namechck;
9504: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9505: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9506: #&logthis("rndseed :$num:$symb");
1.803 albertel 9507: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9508: return "$num1,$num2";
9509: }
9510: }
9511:
9512: sub rndseed_64bit3 {
9513: my ($symb,$courseid,$domain,$username)=@_;
9514: {
9515: use integer;
9516: # strings need to be an even # of cahracters long, it it is odd the
9517: # last characters gets thrown away
9518: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9519: my $symbseed=numval2($symb) << 10;
9520: my $namechck=unpack("%32S*",$username.' ');
9521:
9522: my $nameseed=numval2($username) << 21;
1.443 albertel 9523: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9524: my $courseseed=unpack("%32S*",$courseid.' ');
9525:
9526: my $num1=$symbchck+$symbseed+$namechck;
9527: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9528: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9529: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9530: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9531:
1.503 albertel 9532: return "$num1:$num2";
1.443 albertel 9533: }
9534: }
9535:
1.575 albertel 9536: sub rndseed_64bit4 {
9537: my ($symb,$courseid,$domain,$username)=@_;
9538: {
9539: use integer;
9540: # strings need to be an even # of cahracters long, it it is odd the
9541: # last characters gets thrown away
9542: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9543: my $symbseed=numval3($symb) << 10;
9544: my $namechck=unpack("%32S*",$username.' ');
9545:
9546: my $nameseed=numval3($username) << 21;
9547: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9548: my $courseseed=unpack("%32S*",$courseid.' ');
9549:
9550: my $num1=$symbchck+$symbseed+$namechck;
9551: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9552: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9553: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9554: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9555:
1.575 albertel 9556: return "$num1:$num2";
9557: }
9558: }
9559:
1.675 albertel 9560: sub rndseed_64bit5 {
9561: my ($symb,$courseid,$domain,$username)=@_;
9562: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9563: return "$num1:$num2";
9564: }
9565:
1.366 albertel 9566: sub rndseed_CODE_64bit {
9567: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9568: {
1.366 albertel 9569: use integer;
1.443 albertel 9570: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9571: my $symbseed=numval2($symb);
1.491 albertel 9572: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9573: my $CODEseed=numval(&getCODE());
1.443 albertel 9574: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9575: my $num1=$symbseed+$CODEchck;
9576: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9577: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9578: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9579: if ($_64bit) { $num1=(($num1<<32)>>32); }
9580: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9581: return "$num1:$num2";
1.366 albertel 9582: }
9583: }
9584:
1.575 albertel 9585: sub rndseed_CODE_64bit4 {
9586: my ($symb,$courseid,$domain,$username)=@_;
9587: {
9588: use integer;
9589: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9590: my $symbseed=numval3($symb);
9591: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9592: my $CODEseed=numval3(&getCODE());
9593: my $courseseed=unpack("%32S*",$courseid.' ');
9594: my $num1=$symbseed+$CODEchck;
9595: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9596: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9597: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9598: if ($_64bit) { $num1=(($num1<<32)>>32); }
9599: if ($_64bit) { $num2=(($num2<<32)>>32); }
9600: return "$num1:$num2";
9601: }
9602: }
9603:
1.675 albertel 9604: sub rndseed_CODE_64bit5 {
9605: my ($symb,$courseid,$domain,$username)=@_;
9606: my $code = &getCODE();
9607: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9608: return "$num1:$num2";
9609: }
9610:
1.366 albertel 9611: sub setup_random_from_rndseed {
9612: my ($rndseed)=@_;
1.503 albertel 9613: if ($rndseed =~/([,:])/) {
9614: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9615: &Math::Random::random_set_seed(abs($num1),abs($num2));
9616: } else {
9617: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9618: }
1.36 albertel 9619: }
9620:
1.474 albertel 9621: sub latest_receipt_algorithm_id {
1.835 albertel 9622: return 'receipt3';
1.474 albertel 9623: }
9624:
1.480 www 9625: sub recunique {
9626: my $fucourseid=shift;
9627: my $unique;
1.835 albertel 9628: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9629: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9630: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9631: } else {
9632: $unique=$perlvar{'lonReceipt'};
9633: }
9634: return unpack("%32C*",$unique);
9635: }
9636:
9637: sub recprefix {
9638: my $fucourseid=shift;
9639: my $prefix;
1.835 albertel 9640: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9641: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9642: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9643: } else {
9644: $prefix=$perlvar{'lonHostID'};
9645: }
9646: return unpack("%32C*",$prefix);
9647: }
9648:
1.76 www 9649: sub ireceipt {
1.474 albertel 9650: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9651:
9652: my $return =&recprefix($fucourseid).'-';
9653:
9654: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9655: $env{'request.state'} eq 'construct') {
9656: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9657: return $return;
9658: }
9659:
1.76 www 9660: my $cuname=unpack("%32C*",$funame);
9661: my $cudom=unpack("%32C*",$fudom);
9662: my $cucourseid=unpack("%32C*",$fucourseid);
9663: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9664: my $cunique=&recunique($fucourseid);
1.474 albertel 9665: my $cpart=unpack("%32S*",$part);
1.835 albertel 9666: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9667:
1.790 albertel 9668: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9669:
9670: $return.= ($cunique%$cuname+
9671: $cunique%$cudom+
9672: $cusymb%$cuname+
9673: $cusymb%$cudom+
9674: $cucourseid%$cuname+
9675: $cucourseid%$cudom+
9676: $cpart%$cuname+
9677: $cpart%$cudom);
9678: } else {
9679: $return.= ($cunique%$cuname+
9680: $cunique%$cudom+
9681: $cusymb%$cuname+
9682: $cusymb%$cudom+
9683: $cucourseid%$cuname+
9684: $cucourseid%$cudom);
9685: }
9686: return $return;
1.76 www 9687: }
9688:
9689: sub receipt {
1.474 albertel 9690: my ($part)=@_;
1.790 albertel 9691: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9692: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9693: }
1.260 ng 9694:
1.790 albertel 9695: sub whichuser {
9696: my ($passedsymb)=@_;
9697: my ($symb,$courseid,$domain,$name,$publicuser);
9698: if (defined($env{'form.grade_symb'})) {
9699: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9700: my $allowed=&allowed('vgr',$tmp_courseid);
9701: if (!$allowed &&
9702: exists($env{'request.course.sec'}) &&
9703: $env{'request.course.sec'} !~ /^\s*$/) {
9704: $allowed=&allowed('vgr',$tmp_courseid.
9705: '/'.$env{'request.course.sec'});
9706: }
9707: if ($allowed) {
9708: ($symb)=&get_env_multiple('form.grade_symb');
9709: $courseid=$tmp_courseid;
9710: ($domain)=&get_env_multiple('form.grade_domain');
9711: ($name)=&get_env_multiple('form.grade_username');
9712: return ($symb,$courseid,$domain,$name,$publicuser);
9713: }
9714: }
9715: if (!$passedsymb) {
9716: $symb=&symbread();
9717: } else {
9718: $symb=$passedsymb;
9719: }
9720: $courseid=$env{'request.course.id'};
9721: $domain=$env{'user.domain'};
9722: $name=$env{'user.name'};
9723: if ($name eq 'public' && $domain eq 'public') {
9724: if (!defined($env{'form.username'})) {
9725: $env{'form.username'}.=time.rand(10000000);
9726: }
9727: $name.=$env{'form.username'};
9728: }
9729: return ($symb,$courseid,$domain,$name,$publicuser);
9730:
9731: }
9732:
1.36 albertel 9733: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9734: # returns either the contents of the file or
9735: # -1 if the file doesn't exist
1.481 raeburn 9736: #
9737: # if the target is a file that was uploaded via DOCS,
9738: # a check will be made to see if a current copy exists on the local server,
9739: # if it does this will be served, otherwise a copy will be retrieved from
9740: # the home server for the course and stored in /home/httpd/html/userfiles on
9741: # the local server.
1.472 albertel 9742:
1.36 albertel 9743: sub getfile {
1.538 albertel 9744: my ($file) = @_;
1.609 banghart 9745: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9746: &repcopy($file);
9747: return &readfile($file);
9748: }
9749:
9750: sub repcopy_userfile {
9751: my ($file)=@_;
1.609 banghart 9752: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9753: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9754: my ($cdom,$cnum,$filename) =
1.811 albertel 9755: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9756: my $uri="/uploaded/$cdom/$cnum/$filename";
9757: if (-e "$file") {
1.828 www 9758: # we already have a local copy, check it out
1.538 albertel 9759: my @fileinfo = stat($file);
1.828 www 9760: my $rtncode;
9761: my $info;
1.538 albertel 9762: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9763: if ($lwpresp ne 'ok') {
1.828 www 9764: # there is no such file anymore, even though we had a local copy
1.482 albertel 9765: if ($rtncode eq '404') {
1.538 albertel 9766: unlink($file);
1.482 albertel 9767: }
9768: return -1;
9769: }
9770: if ($info < $fileinfo[9]) {
1.828 www 9771: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9772: return 'ok';
1.828 www 9773: } else {
9774: # the file is outdated, get rid of it
9775: unlink($file);
1.482 albertel 9776: }
1.828 www 9777: }
9778: # one way or the other, at this point, we don't have the file
9779: # construct the correct path for the file
9780: my @parts = ($cdom,$cnum);
9781: if ($filename =~ m|^(.+)/[^/]+$|) {
9782: push @parts, split(/\//,$1);
9783: }
9784: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9785: foreach my $part (@parts) {
9786: $path .= '/'.$part;
9787: if (!-e $path) {
9788: mkdir($path,0770);
1.482 albertel 9789: }
9790: }
1.828 www 9791: # now the path exists for sure
9792: # get a user agent
9793: my $ua=new LWP::UserAgent;
9794: my $transferfile=$file.'.in.transfer';
9795: # FIXME: this should flock
9796: if (-e $transferfile) { return 'ok'; }
9797: my $request;
9798: $uri=~s/^\///;
1.980 raeburn 9799: my $homeserver = &homeserver($cnum,$cdom);
9800: my $protocol = $protocol{$homeserver};
9801: $protocol = 'http' if ($protocol ne 'https');
9802: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9803: my $response=$ua->request($request,$transferfile);
9804: # did it work?
9805: if ($response->is_error()) {
9806: unlink($transferfile);
9807: &logthis("Userfile repcopy failed for $uri");
9808: return -1;
9809: }
9810: # worked, rename the transfer file
9811: rename($transferfile,$file);
1.607 raeburn 9812: return 'ok';
1.481 raeburn 9813: }
9814:
1.517 albertel 9815: sub tokenwrapper {
9816: my $uri=shift;
1.980 raeburn 9817: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9818: $uri=~s|^/||;
1.620 albertel 9819: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9820: my $token=$1;
1.552 albertel 9821: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9822: if ($udom && $uname && $file) {
9823: $file=~s|(\?\.*)*$||;
1.949 raeburn 9824: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9825: my $homeserver = &homeserver($uname,$udom);
9826: my $protocol = $protocol{$homeserver};
9827: $protocol = 'http' if ($protocol ne 'https');
9828: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9829: (($uri=~/\?/)?'&':'?').'token='.$token.
9830: '&tokenissued='.$perlvar{'lonHostID'};
9831: } else {
9832: return '/adm/notfound.html';
9833: }
9834: }
9835:
1.828 www 9836: # call with reqtype HEAD: get last modification time
9837: # call with reqtype GET: get the file contents
9838: # Do not call this with reqtype GET for large files! It loads everything into memory
9839: #
1.481 raeburn 9840: sub getuploaded {
9841: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9842: $uri=~s/^\///;
1.980 raeburn 9843: my $homeserver = &homeserver($cnum,$cdom);
9844: my $protocol = $protocol{$homeserver};
9845: $protocol = 'http' if ($protocol ne 'https');
9846: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9847: my $ua=new LWP::UserAgent;
9848: my $request=new HTTP::Request($reqtype,$uri);
9849: my $response=$ua->request($request);
9850: $$rtncode = $response->code;
1.482 albertel 9851: if (! $response->is_success()) {
9852: return 'failed';
9853: }
9854: if ($reqtype eq 'HEAD') {
1.486 www 9855: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9856: } elsif ($reqtype eq 'GET') {
9857: $$info = $response->content;
1.472 albertel 9858: }
1.482 albertel 9859: return 'ok';
1.36 albertel 9860: }
9861:
1.481 raeburn 9862: sub readfile {
9863: my $file = shift;
9864: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9865: my $fh;
9866: open($fh,"<$file");
9867: my $a='';
1.800 albertel 9868: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9869: return $a;
9870: }
9871:
1.36 albertel 9872: sub filelocation {
1.590 banghart 9873: my ($dir,$file) = @_;
9874: my $location;
9875: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9876:
9877: if ($file =~ m-^/adm/-) {
9878: $file=~s-^/adm/wrapper/-/-;
9879: $file=~s-^/adm/coursedocs/showdoc/-/-;
9880: }
1.882 albertel 9881:
1.590 banghart 9882: if ($file=~m:^/~:) { # is a contruction space reference
9883: $location = $file;
9884: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9885: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9886: # is a correct contruction space reference
9887: $location = $file;
1.956 raeburn 9888: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9889: $location = $file;
1.609 banghart 9890: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9891: my ($udom,$uname,$filename)=
1.811 albertel 9892: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9893: my $home=&homeserver($uname,$udom);
9894: my $is_me=0;
9895: my @ids=¤t_machine_ids();
9896: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9897: if ($is_me) {
1.1117 foxr 9898: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9899: } else {
9900: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9901: $udom.'/'.$uname.'/'.$filename;
9902: }
1.882 albertel 9903: } elsif ($file =~ m-^/adm/-) {
9904: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9905: } else {
9906: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9907: $file=~s:^/res/:/:;
9908: if ( !( $file =~ m:^/:) ) {
9909: $location = $dir. '/'.$file;
9910: } else {
9911: $location = '/home/httpd/html/res'.$file;
9912: }
1.59 albertel 9913: }
1.590 banghart 9914: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9915: while ($location=~m{/\.\./}) {
9916: if ($location =~ m{/[^/]+/\.\./}) {
9917: $location=~ s{/[^/]+/\.\./}{/}g;
9918: } else {
9919: $location=~ s{/\.\./}{/}g;
9920: }
9921: } #remove dir/..
1.590 banghart 9922: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9923: return $location;
1.46 www 9924: }
1.36 albertel 9925:
1.46 www 9926: sub hreflocation {
9927: my ($dir,$file)=@_;
1.980 raeburn 9928: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9929: $file=filelocation($dir,$file);
1.700 albertel 9930: } elsif ($file=~m-^/adm/-) {
9931: $file=~s-^/adm/wrapper/-/-;
9932: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9933: }
9934: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9935: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9936: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9937: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9938: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9939: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9940: -/uploaded/$1/$2/-x;
1.46 www 9941: }
1.913 albertel 9942: if ($file=~ m{^/userfiles/}) {
9943: $file =~ s{^/userfiles/}{/uploaded/};
9944: }
1.462 albertel 9945: return $file;
1.465 albertel 9946: }
9947:
9948: sub current_machine_domains {
1.853 albertel 9949: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9950: }
9951:
9952: sub machine_domains {
9953: my ($hostname) = @_;
1.465 albertel 9954: my @domains;
1.838 albertel 9955: my %hostname = &all_hostnames();
1.465 albertel 9956: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9957: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9958: if ($hostname eq $name) {
1.844 albertel 9959: push(@domains,&host_domain($id));
1.465 albertel 9960: }
9961: }
9962: return @domains;
9963: }
9964:
9965: sub current_machine_ids {
1.853 albertel 9966: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9967: }
9968:
9969: sub machine_ids {
9970: my ($hostname) = @_;
9971: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9972: my @ids;
1.888 albertel 9973: my %name_to_host = &all_names();
1.889 albertel 9974: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9975: return @{ $name_to_host{$hostname} };
9976: }
9977: return;
1.31 www 9978: }
9979:
1.824 raeburn 9980: sub additional_machine_domains {
9981: my @domains;
9982: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9983: while( my $line = <$fh>) {
9984: $line =~ s/\s//g;
9985: push(@domains,$line);
9986: }
9987: return @domains;
9988: }
9989:
9990: sub default_login_domain {
9991: my $domain = $perlvar{'lonDefDomain'};
9992: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9993: foreach my $posdom (¤t_machine_domains(),
9994: &additional_machine_domains()) {
9995: if (lc($posdom) eq lc($testdomain)) {
9996: $domain=$posdom;
9997: last;
9998: }
9999: }
10000: return $domain;
10001: }
10002:
1.31 www 10003: # ------------------------------------------------------------- Declutters URLs
10004:
10005: sub declutter {
10006: my $thisfn=shift;
1.569 albertel 10007: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10008: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10009: $thisfn=~s/^\///;
1.697 albertel 10010: $thisfn=~s|^adm/wrapper/||;
10011: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10012: $thisfn=~s/^res\///;
1.1032 raeburn 10013: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10014: $thisfn=~s/\?.+$//;
10015: }
1.268 www 10016: return $thisfn;
10017: }
10018:
10019: # ------------------------------------------------------------- Clutter up URLs
10020:
10021: sub clutter {
10022: my $thisfn='/'.&declutter(shift);
1.887 albertel 10023: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10024: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10025: $thisfn='/res'.$thisfn;
10026: }
1.1031 raeburn 10027: if ($thisfn !~m|^/adm|) {
10028: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10029: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10030: } else {
10031: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10032: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10033: if ($embstyle eq 'ssi'
10034: || ($embstyle eq 'hdn')
10035: || ($embstyle eq 'rat')
10036: || ($embstyle eq 'prv')
10037: || ($embstyle eq 'ign')) {
10038: #do nothing with these
10039: } elsif (($embstyle eq 'img')
1.695 albertel 10040: || ($embstyle eq 'emb')
10041: || ($embstyle eq 'wrp')) {
10042: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10043: } elsif ($embstyle eq 'unk'
10044: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10045: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10046: } else {
1.718 www 10047: # &logthis("Got a blank emb style");
1.695 albertel 10048: }
1.694 albertel 10049: }
10050: }
1.31 www 10051: return $thisfn;
1.12 www 10052: }
10053:
1.787 albertel 10054: sub clutter_with_no_wrapper {
10055: my $uri = &clutter(shift);
10056: if ($uri =~ m-^/adm/-) {
10057: $uri =~ s-^/adm/wrapper/-/-;
10058: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10059: }
10060: return $uri;
10061: }
10062:
1.557 albertel 10063: sub freeze_escape {
10064: my ($value)=@_;
10065: if (ref($value)) {
10066: $value=&nfreeze($value);
10067: return '__FROZEN__'.&escape($value);
10068: }
10069: return &escape($value);
10070: }
10071:
1.11 www 10072:
1.557 albertel 10073: sub thaw_unescape {
10074: my ($value)=@_;
10075: if ($value =~ /^__FROZEN__/) {
10076: substr($value,0,10,undef);
10077: $value=&unescape($value);
10078: return &thaw($value);
10079: }
10080: return &unescape($value);
10081: }
10082:
1.436 albertel 10083: sub correct_line_ends {
10084: my ($result)=@_;
10085: $$result =~s/\r\n/\n/mg;
10086: $$result =~s/\r/\n/mg;
1.415 albertel 10087: }
1.1 albertel 10088: # ================================================================ Main Program
10089:
1.184 www 10090: sub goodbye {
1.204 albertel 10091: &logthis("Starting Shut down");
1.443 albertel 10092: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10093: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10094: #converted
1.599 albertel 10095: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10096: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10097: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10098: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10099: #1.1 only
1.870 albertel 10100: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10101: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10102: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10103: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10104: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10105: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10106: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10107: &flushcourselogs();
10108: &logthis("Shutting down");
10109: }
10110:
1.852 albertel 10111: sub get_dns {
1.869 albertel 10112: my ($url,$func,$ignore_cache) = @_;
10113: if (!$ignore_cache) {
10114: my ($content,$cached)=
10115: &Apache::lonnet::is_cached_new('dns',$url);
10116: if ($cached) {
10117: &$func($content);
10118: return;
10119: }
10120: }
10121:
10122: my %alldns;
1.852 albertel 10123: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10124: foreach my $dns (<$config>) {
10125: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10126: my $line = $1;
10127: my ($host,$protocol) = split(/:/,$line);
10128: if ($protocol ne 'https') {
10129: $protocol = 'http';
10130: }
10131: $alldns{$host} = $protocol;
1.869 albertel 10132: }
10133: while (%alldns) {
10134: my ($dns) = keys(%alldns);
1.852 albertel 10135: my $ua=new LWP::UserAgent;
1.979 raeburn 10136: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10137: my $response=$ua->request($request);
1.979 raeburn 10138: delete($alldns{$dns});
1.852 albertel 10139: next if ($response->is_error());
10140: my @content = split("\n",$response->content);
1.869 albertel 10141: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10142: &$func(\@content);
1.869 albertel 10143: return;
1.852 albertel 10144: }
10145: close($config);
1.871 albertel 10146: my $which = (split('/',$url))[3];
10147: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10148: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10149: my @content = <$config>;
10150: &$func(\@content);
10151: return;
1.852 albertel 10152: }
1.327 albertel 10153: # ------------------------------------------------------------ Read domain file
10154: {
1.852 albertel 10155: my $loaded;
1.846 albertel 10156: my %domain;
10157:
1.852 albertel 10158: sub parse_domain_tab {
10159: my ($lines) = @_;
10160: foreach my $line (@$lines) {
10161: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10162:
1.846 albertel 10163: chomp($line);
1.852 albertel 10164: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10165: my %this_domain;
10166: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10167: 'lang_def', 'city', 'longi', 'lati',
10168: 'primary') {
10169: $this_domain{$field} = shift(@elements);
10170: }
10171: $domain{$name} = \%this_domain;
1.852 albertel 10172: }
10173: }
1.864 albertel 10174:
10175: sub reset_domain_info {
10176: undef($loaded);
10177: undef(%domain);
10178: }
10179:
1.852 albertel 10180: sub load_domain_tab {
1.869 albertel 10181: my ($ignore_cache) = @_;
10182: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10183: my $fh;
10184: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10185: my @lines = <$fh>;
10186: &parse_domain_tab(\@lines);
1.448 albertel 10187: }
1.852 albertel 10188: close($fh);
10189: $loaded = 1;
1.327 albertel 10190: }
1.846 albertel 10191:
10192: sub domain {
1.852 albertel 10193: &load_domain_tab() if (!$loaded);
10194:
1.846 albertel 10195: my ($name,$what) = @_;
10196: return if ( !exists($domain{$name}) );
10197:
10198: if (!$what) {
10199: return $domain{$name}{'description'};
10200: }
10201: return $domain{$name}{$what};
10202: }
1.974 raeburn 10203:
10204: sub domain_info {
10205: &load_domain_tab() if (!$loaded);
10206: return %domain;
10207: }
10208:
1.327 albertel 10209: }
10210:
10211:
1.1 albertel 10212: # ------------------------------------------------------------- Read hosts file
10213: {
1.838 albertel 10214: my %hostname;
1.844 albertel 10215: my %hostdom;
1.845 albertel 10216: my %libserv;
1.852 albertel 10217: my $loaded;
1.888 albertel 10218: my %name_to_host;
1.1074 raeburn 10219: my %internetdom;
1.1107 raeburn 10220: my %LC_dns_serv;
1.852 albertel 10221:
10222: sub parse_hosts_tab {
10223: my ($file) = @_;
10224: foreach my $configline (@$file) {
10225: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10226: chomp($configline);
10227: if ($configline =~ /^\^/) {
10228: if ($configline =~ /^\^([\w.\-]+)/) {
10229: $LC_dns_serv{$1} = 1;
10230: }
10231: next;
10232: }
1.1074 raeburn 10233: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10234: $name=~s/\s//g;
10235: if ($id && $domain && $role && $name) {
10236: $hostname{$id}=$name;
1.888 albertel 10237: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10238: $hostdom{$id}=$domain;
10239: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10240: if (defined($protocol)) {
10241: if ($protocol eq 'https') {
10242: $protocol{$id} = $protocol;
10243: } else {
10244: $protocol{$id} = 'http';
10245: }
1.968 raeburn 10246: } else {
1.969 raeburn 10247: $protocol{$id} = 'http';
1.968 raeburn 10248: }
1.1074 raeburn 10249: if (defined($intdom)) {
10250: $internetdom{$id} = $intdom;
10251: }
1.852 albertel 10252: }
10253: }
10254: }
1.864 albertel 10255:
10256: sub reset_hosts_info {
1.897 albertel 10257: &purge_remembered();
1.864 albertel 10258: &reset_domain_info();
10259: &reset_hosts_ip_info();
1.892 albertel 10260: undef(%name_to_host);
1.864 albertel 10261: undef(%hostname);
10262: undef(%hostdom);
10263: undef(%libserv);
10264: undef($loaded);
10265: }
1.1 albertel 10266:
1.852 albertel 10267: sub load_hosts_tab {
1.869 albertel 10268: my ($ignore_cache) = @_;
10269: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10270: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10271: my @config = <$config>;
10272: &parse_hosts_tab(\@config);
10273: close($config);
10274: $loaded=1;
1.1 albertel 10275: }
1.852 albertel 10276:
1.838 albertel 10277: sub hostname {
1.852 albertel 10278: &load_hosts_tab() if (!$loaded);
10279:
1.838 albertel 10280: my ($lonid) = @_;
10281: return $hostname{$lonid};
10282: }
1.845 albertel 10283:
1.838 albertel 10284: sub all_hostnames {
1.852 albertel 10285: &load_hosts_tab() if (!$loaded);
10286:
1.838 albertel 10287: return %hostname;
10288: }
1.845 albertel 10289:
1.888 albertel 10290: sub all_names {
10291: &load_hosts_tab() if (!$loaded);
10292:
10293: return %name_to_host;
10294: }
10295:
1.974 raeburn 10296: sub all_host_domain {
10297: &load_hosts_tab() if (!$loaded);
10298: return %hostdom;
10299: }
10300:
1.845 albertel 10301: sub is_library {
1.852 albertel 10302: &load_hosts_tab() if (!$loaded);
10303:
1.845 albertel 10304: return exists($libserv{$_[0]});
10305: }
10306:
10307: sub all_library {
1.852 albertel 10308: &load_hosts_tab() if (!$loaded);
10309:
1.845 albertel 10310: return %libserv;
10311: }
10312:
1.1062 droeschl 10313: sub unique_library {
10314: #2x reverse removes all hostnames that appear more than once
10315: my %unique = reverse &all_library();
10316: return reverse %unique;
10317: }
10318:
1.841 albertel 10319: sub get_servers {
1.852 albertel 10320: &load_hosts_tab() if (!$loaded);
10321:
1.841 albertel 10322: my ($domain,$type) = @_;
10323: my %possible_hosts = ($type eq 'library') ? %libserv
10324: : %hostname;
10325: my %result;
1.842 albertel 10326: if (ref($domain) eq 'ARRAY') {
10327: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10328: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10329: $result{$host} = $hostname;
10330: }
10331: }
10332: } else {
10333: while ( my ($host,$hostname) = each(%possible_hosts)) {
10334: if ($hostdom{$host} eq $domain) {
10335: $result{$host} = $hostname;
10336: }
1.841 albertel 10337: }
10338: }
10339: return %result;
10340: }
1.845 albertel 10341:
1.1062 droeschl 10342: sub get_unique_servers {
10343: my %unique = reverse &get_servers(@_);
10344: return reverse %unique;
10345: }
10346:
1.844 albertel 10347: sub host_domain {
1.852 albertel 10348: &load_hosts_tab() if (!$loaded);
10349:
1.844 albertel 10350: my ($lonid) = @_;
10351: return $hostdom{$lonid};
10352: }
10353:
1.841 albertel 10354: sub all_domains {
1.852 albertel 10355: &load_hosts_tab() if (!$loaded);
10356:
1.841 albertel 10357: my %seen;
10358: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10359: return @uniq;
10360: }
1.1074 raeburn 10361:
10362: sub internet_dom {
10363: &load_hosts_tab() if (!$loaded);
10364:
10365: my ($lonid) = @_;
10366: return $internetdom{$lonid};
10367: }
1.1107 raeburn 10368:
10369: sub is_LC_dns {
10370: &load_hosts_tab() if (!$loaded);
10371:
10372: my ($hostname) = @_;
10373: return exists($LC_dns_serv{$hostname});
10374: }
10375:
1.1 albertel 10376: }
10377:
1.847 albertel 10378: {
10379: my %iphost;
1.856 albertel 10380: my %name_to_ip;
10381: my %lonid_to_ip;
1.869 albertel 10382:
1.847 albertel 10383: sub get_hosts_from_ip {
10384: my ($ip) = @_;
10385: my %iphosts = &get_iphost();
10386: if (ref($iphosts{$ip})) {
10387: return @{$iphosts{$ip}};
10388: }
10389: return;
1.839 albertel 10390: }
1.864 albertel 10391:
10392: sub reset_hosts_ip_info {
10393: undef(%iphost);
10394: undef(%name_to_ip);
10395: undef(%lonid_to_ip);
10396: }
1.856 albertel 10397:
10398: sub get_host_ip {
10399: my ($lonid) = @_;
10400: if (exists($lonid_to_ip{$lonid})) {
10401: return $lonid_to_ip{$lonid};
10402: }
10403: my $name=&hostname($lonid);
10404: my $ip = gethostbyname($name);
10405: return if (!$ip || length($ip) ne 4);
10406: $ip=inet_ntoa($ip);
10407: $name_to_ip{$name} = $ip;
10408: $lonid_to_ip{$lonid} = $ip;
10409: return $ip;
10410: }
1.847 albertel 10411:
10412: sub get_iphost {
1.869 albertel 10413: my ($ignore_cache) = @_;
1.894 albertel 10414:
1.869 albertel 10415: if (!$ignore_cache) {
10416: if (%iphost) {
10417: return %iphost;
10418: }
10419: my ($ip_info,$cached)=
10420: &Apache::lonnet::is_cached_new('iphost','iphost');
10421: if ($cached) {
10422: %iphost = %{$ip_info->[0]};
10423: %name_to_ip = %{$ip_info->[1]};
10424: %lonid_to_ip = %{$ip_info->[2]};
10425: return %iphost;
10426: }
10427: }
1.894 albertel 10428:
10429: # get yesterday's info for fallback
10430: my %old_name_to_ip;
10431: my ($ip_info,$cached)=
10432: &Apache::lonnet::is_cached_new('iphost','iphost');
10433: if ($cached) {
10434: %old_name_to_ip = %{$ip_info->[1]};
10435: }
10436:
1.888 albertel 10437: my %name_to_host = &all_names();
10438: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10439: my $ip;
10440: if (!exists($name_to_ip{$name})) {
10441: $ip = gethostbyname($name);
10442: if (!$ip || length($ip) ne 4) {
1.894 albertel 10443: if (defined($old_name_to_ip{$name})) {
10444: $ip = $old_name_to_ip{$name};
10445: &logthis("Can't find $name defaulting to old $ip");
10446: } else {
10447: &logthis("Name $name no IP found");
10448: next;
10449: }
10450: } else {
10451: $ip=inet_ntoa($ip);
1.847 albertel 10452: }
10453: $name_to_ip{$name} = $ip;
10454: } else {
10455: $ip = $name_to_ip{$name};
1.653 albertel 10456: }
1.888 albertel 10457: foreach my $id (@{ $name_to_host{$name} }) {
10458: $lonid_to_ip{$id} = $ip;
10459: }
10460: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10461: }
1.869 albertel 10462: &Apache::lonnet::do_cache_new('iphost','iphost',
10463: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10464: 48*60*60);
1.869 albertel 10465:
1.847 albertel 10466: return %iphost;
1.598 albertel 10467: }
10468:
1.992 raeburn 10469: #
10470: # Given a DNS returns the loncapa host name for that DNS
10471: #
10472: sub host_from_dns {
10473: my ($dns) = @_;
10474: my @hosts;
10475: my $ip;
10476:
1.993 raeburn 10477: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10478: $ip = $name_to_ip{$dns};
10479: }
10480: if (!$ip) {
10481: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10482: if (length($ip) == 4) {
10483: $ip = &IO::Socket::inet_ntoa($ip);
10484: }
10485: }
10486: if ($ip) {
10487: @hosts = get_hosts_from_ip($ip);
10488: return $hosts[0];
10489: }
10490: return undef;
1.986 foxr 10491: }
1.992 raeburn 10492:
1.1074 raeburn 10493: sub get_internet_names {
10494: my ($lonid) = @_;
10495: return if ($lonid eq '');
10496: my ($idnref,$cached)=
10497: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10498: if ($cached) {
10499: return $idnref;
10500: }
10501: my $ip = &get_host_ip($lonid);
10502: my @hosts = &get_hosts_from_ip($ip);
10503: my %iphost = &get_iphost();
10504: my (@idns,%seen);
10505: foreach my $id (@hosts) {
10506: my $dom = &host_domain($id);
10507: my $prim_id = &domain($dom,'primary');
10508: my $prim_ip = &get_host_ip($prim_id);
10509: next if ($seen{$prim_ip});
10510: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10511: foreach my $id (@{$iphost{$prim_ip}}) {
10512: my $intdom = &internet_dom($id);
10513: unless (grep(/^\Q$intdom\E$/,@idns)) {
10514: push(@idns,$intdom);
10515: }
10516: }
10517: }
10518: $seen{$prim_ip} = 1;
10519: }
10520: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10521: }
10522:
1.986 foxr 10523: }
10524:
1.1079 raeburn 10525: sub all_loncaparevs {
10526: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
10527: }
10528:
1.862 albertel 10529: BEGIN {
10530:
10531: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10532: unless ($readit) {
10533: {
10534: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10535: %perlvar = (%perlvar,%{$configvars});
10536: }
10537:
10538:
1.1 albertel 10539: # ------------------------------------------------------ Read spare server file
10540: {
1.448 albertel 10541: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10542:
10543: while (my $configline=<$config>) {
10544: chomp($configline);
1.284 matthew 10545: if ($configline) {
1.784 albertel 10546: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10547: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10548: push(@{ $spareid{$type} }, $host);
1.1 albertel 10549: }
10550: }
1.448 albertel 10551: close($config);
1.1 albertel 10552: }
1.11 www 10553: # ------------------------------------------------------------ Read permissions
10554: {
1.448 albertel 10555: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10556:
10557: while (my $configline=<$config>) {
1.448 albertel 10558: chomp($configline);
10559: if ($configline) {
10560: my ($role,$perm)=split(/ /,$configline);
10561: if ($perm ne '') { $pr{$role}=$perm; }
10562: }
1.11 www 10563: }
1.448 albertel 10564: close($config);
1.11 www 10565: }
10566:
10567: # -------------------------------------------- Read plain texts for permissions
10568: {
1.448 albertel 10569: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10570:
10571: while (my $configline=<$config>) {
1.448 albertel 10572: chomp($configline);
10573: if ($configline) {
1.742 raeburn 10574: my ($short,@plain)=split(/:/,$configline);
10575: %{$prp{$short}} = ();
10576: if (@plain > 0) {
10577: $prp{$short}{'std'} = $plain[0];
10578: for (my $i=1; $i<@plain; $i++) {
10579: $prp{$short}{'alt'.$i} = $plain[$i];
10580: }
10581: }
1.448 albertel 10582: }
1.135 www 10583: }
1.448 albertel 10584: close($config);
1.135 www 10585: }
10586:
10587: # ---------------------------------------------------------- Read package table
10588: {
1.448 albertel 10589: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10590:
10591: while (my $configline=<$config>) {
1.483 albertel 10592: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10593: chomp($configline);
10594: my ($short,$plain)=split(/:/,$configline);
10595: my ($pack,$name)=split(/\&/,$short);
10596: if ($plain ne '') {
10597: $packagetab{$pack.'&'.$name.'&name'}=$name;
10598: $packagetab{$short}=$plain;
10599: }
1.11 www 10600: }
1.448 albertel 10601: close($config);
1.329 matthew 10602: }
10603:
1.1073 raeburn 10604: # ---------------------------------------------------------- Read loncaparev table
10605: {
10606: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10607: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10608: while (my $configline=<$config>) {
10609: chomp($configline);
10610: my ($hostid,$loncaparev)=split(/:/,$configline);
10611: $loncaparevs{$hostid}=$loncaparev;
10612: }
10613: close($config);
10614: }
10615: }
10616: }
10617:
1.1074 raeburn 10618: # ---------------------------------------------------------- Read serverhostID table
10619: {
10620: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10621: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10622: while (my $configline=<$config>) {
10623: chomp($configline);
10624: my ($name,$id)=split(/:/,$configline);
10625: $serverhomeIDs{$name}=$id;
10626: }
10627: close($config);
10628: }
10629: }
10630: }
10631:
1.1079 raeburn 10632: {
10633: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10634: if (-e $file) {
10635: my $parser = HTML::LCParser->new($file);
10636: while (my $token = $parser->get_token()) {
10637: if ($token->[0] eq 'S') {
10638: my $item = $token->[1];
10639: my $name = $token->[2]{'name'};
10640: my $value = $token->[2]{'value'};
10641: if ($item ne '' && $name ne '' && $value ne '') {
10642: my $release = $parser->get_text();
10643: $release =~ s/(^\s*|\s*$ )//gx;
10644: $needsrelease{$item.':'.$name.':'.$value} = $release;
10645: }
10646: }
10647: }
10648: }
1.1073 raeburn 10649: }
10650:
1.329 matthew 10651: # ------------- set up temporary directory
10652: {
1.1117 foxr 10653: $tmpdir = LONCAPA::tempdir();
1.329 matthew 10654:
1.11 www 10655: }
10656:
1.794 albertel 10657: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10658: 'compress_threshold'=> 20_000,
10659: });
1.185 www 10660:
1.281 www 10661: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10662: $dumpcount=0;
1.958 www 10663: $locknum=0;
1.22 www 10664:
1.163 harris41 10665: &logtouch();
1.672 albertel 10666: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10667: $readit=1;
1.564 albertel 10668: {
10669: use integer;
10670: my $test=(2**32)+1;
1.568 albertel 10671: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10672: &logthis(" Detected 64bit platform ($_64bit)");
10673: }
1.195 www 10674: }
1.1 albertel 10675: }
1.179 www 10676:
1.1 albertel 10677: 1;
1.191 harris41 10678: __END__
10679:
1.243 albertel 10680: =pod
10681:
1.191 harris41 10682: =head1 NAME
10683:
1.243 albertel 10684: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10685:
10686: =head1 SYNOPSIS
10687:
1.243 albertel 10688: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10689:
10690: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10691:
1.243 albertel 10692: Common parameters:
10693:
10694: =over 4
10695:
10696: =item *
10697:
10698: $uname : an internal username (if $cname expecting a course Id specifically)
10699:
10700: =item *
10701:
10702: $udom : a domain (if $cdom expecting a course's domain specifically)
10703:
10704: =item *
10705:
10706: $symb : a resource instance identifier
10707:
10708: =item *
10709:
10710: $namespace : the name of a .db file that contains the data needed or
10711: being set.
10712:
10713: =back
10714:
1.394 bowersj2 10715: =head1 OVERVIEW
1.191 harris41 10716:
1.394 bowersj2 10717: lonnet provides subroutines which interact with the
10718: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10719: about classes, users, and resources.
1.243 albertel 10720:
10721: For many of these objects you can also use this to store data about
10722: them or modify them in various ways.
1.191 harris41 10723:
1.394 bowersj2 10724: =head2 Symbs
1.191 harris41 10725:
1.394 bowersj2 10726: To identify a specific instance of a resource, LON-CAPA uses symbols
10727: or "symbs"X<symb>. These identifiers are built from the URL of the
10728: map, the resource number of the resource in the map, and the URL of
10729: the resource itself. The latter is somewhat redundant, but might help
10730: if maps change.
10731:
10732: An example is
10733:
10734: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10735:
10736: The respective map entry is
10737:
10738: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10739: title="Problem 2">
10740: </resource>
10741:
10742: Symbs are used by the random number generator, as well as to store and
10743: restore data specific to a certain instance of for example a problem.
10744:
10745: =head2 Storing And Retrieving Data
10746:
10747: X<store()>X<cstore()>X<restore()>Three of the most important functions
10748: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10749: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10750: is is the non-critical message twin of cstore. These functions are for
10751: handlers to store a perl hash to a user's permanent data space in an
10752: easy manner, and to retrieve it again on another call. It is expected
10753: that a handler would use this once at the beginning to retrieve data,
10754: and then again once at the end to send only the new data back.
10755:
10756: The data is stored in the user's data directory on the user's
10757: homeserver under the ID of the course.
10758:
10759: The hash that is returned by restore will have all of the previous
10760: value for all of the elements of the hash.
10761:
10762: Example:
10763:
10764: #creating a hash
10765: my %hash;
10766: $hash{'foo'}='bar';
10767:
10768: #storing it
10769: &Apache::lonnet::cstore(\%hash);
10770:
10771: #changing a value
10772: $hash{'foo'}='notbar';
10773:
10774: #adding a new value
10775: $hash{'bar'}='foo';
10776: &Apache::lonnet::cstore(\%hash);
10777:
10778: #retrieving the hash
10779: my %history=&Apache::lonnet::restore();
10780:
10781: #print the hash
10782: foreach my $key (sort(keys(%history))) {
10783: print("\%history{$key} = $history{$key}");
10784: }
10785:
10786: Will print out:
1.191 harris41 10787:
1.394 bowersj2 10788: %history{1:foo} = bar
10789: %history{1:keys} = foo:timestamp
10790: %history{1:timestamp} = 990455579
10791: %history{2:bar} = foo
10792: %history{2:foo} = notbar
10793: %history{2:keys} = foo:bar:timestamp
10794: %history{2:timestamp} = 990455580
10795: %history{bar} = foo
10796: %history{foo} = notbar
10797: %history{timestamp} = 990455580
10798: %history{version} = 2
10799:
10800: Note that the special hash entries C<keys>, C<version> and
10801: C<timestamp> were added to the hash. C<version> will be equal to the
10802: total number of versions of the data that have been stored. The
10803: C<timestamp> attribute will be the UNIX time the hash was
10804: stored. C<keys> is available in every historical section to list which
10805: keys were added or changed at a specific historical revision of a
10806: hash.
10807:
10808: B<Warning>: do not store the hash that restore returns directly. This
10809: will cause a mess since it will restore the historical keys as if the
10810: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10811:
1.394 bowersj2 10812: Calling convention:
1.191 harris41 10813:
1.394 bowersj2 10814: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10815: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10816:
1.394 bowersj2 10817: For more detailed information, see lonnet specific documentation.
1.191 harris41 10818:
1.394 bowersj2 10819: =head1 RETURN MESSAGES
1.191 harris41 10820:
1.394 bowersj2 10821: =over 4
1.191 harris41 10822:
1.394 bowersj2 10823: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10824:
1.394 bowersj2 10825: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10826: when the connection is brought back up
1.191 harris41 10827:
1.394 bowersj2 10828: =item * B<con_failed>: unable to contact remote host and unable to save message
10829: for later delivery
1.191 harris41 10830:
1.967 bisitz 10831: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10832:
1.394 bowersj2 10833: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10834: that was requested
1.191 harris41 10835:
1.243 albertel 10836: =back
1.191 harris41 10837:
1.243 albertel 10838: =head1 PUBLIC SUBROUTINES
1.191 harris41 10839:
1.243 albertel 10840: =head2 Session Environment Functions
1.191 harris41 10841:
1.243 albertel 10842: =over 4
1.191 harris41 10843:
1.394 bowersj2 10844: =item *
10845: X<appenv()>
1.949 raeburn 10846: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10847: the user envirnoment file, and will be restored for each access this
1.620 albertel 10848: user makes during this session, also modifies the %env for the current
1.949 raeburn 10849: process. Optional rolesarrayref - if defined contains a reference to an array
10850: of roles which are exempt from the restriction on modifying user.role entries
10851: in the user's environment.db and in %env.
1.191 harris41 10852:
10853: =item *
1.394 bowersj2 10854: X<delenv()>
1.987 raeburn 10855: B<delenv($delthis,$regexp)>: removes all items from the session
10856: environment file that begin with $delthis. If the
10857: optional second arg - $regexp - is true, $delthis is treated as a
10858: regular expression, otherwise \Q$delthis\E is used.
10859: The values are also deleted from the current processes %env.
1.191 harris41 10860:
1.795 albertel 10861: =item * get_env_multiple($name)
10862:
10863: gets $name from the %env hash, it seemlessly handles the cases where multiple
10864: values may be defined and end up as an array ref.
10865:
10866: returns an array of values
10867:
1.243 albertel 10868: =back
10869:
10870: =head2 User Information
1.191 harris41 10871:
1.243 albertel 10872: =over 4
1.191 harris41 10873:
10874: =item *
1.394 bowersj2 10875: X<queryauthenticate()>
10876: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10877: authentication scheme
10878:
10879: =item *
1.394 bowersj2 10880: X<authenticate()>
1.1073 raeburn 10881: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10882: authenticate user from domain's lib servers (first use the current
10883: one). C<$upass> should be the users password.
1.1073 raeburn 10884: $checkdefauth is optional (value is 1 if a check should be made to
10885: authenticate user using default authentication method, and allow
10886: account creation if username does not have account in the domain).
10887: $clientcancheckhost is optional (value is 1 if checking whether the
10888: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10889:
10890: =item *
1.394 bowersj2 10891: X<homeserver()>
10892: B<homeserver($uname,$udom)>: find the server which has
10893: the user's directory and files (there must be only one), this caches
10894: the answer, and also caches if there is a borken connection.
1.191 harris41 10895:
10896: =item *
1.394 bowersj2 10897: X<idget()>
10898: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10899: (IDs are a unique resource in a domain, there must be only 1 ID per
10900: username, and only 1 username per ID in a specific domain) (returns
10901: hash: id=>name,id=>name)
1.191 harris41 10902:
10903: =item *
1.394 bowersj2 10904: X<idrget()>
10905: B<idrget($udom,@unames)>: find the IDs behind a list of
10906: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10907:
10908: =item *
1.394 bowersj2 10909: X<idput()>
10910: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10911:
10912: =item *
1.394 bowersj2 10913: X<rolesinit()>
10914: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10915:
10916: =item *
1.551 albertel 10917: X<getsection()>
10918: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10919: course $cname, return section name/number or '' for "not in course"
10920: and '-1' for "no section"
10921:
10922: =item *
1.394 bowersj2 10923: X<userenvironment()>
10924: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10925: passed in @what from the requested user's environment, returns a hash
10926:
1.858 raeburn 10927: =item *
10928: X<userlog_query()>
1.859 albertel 10929: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10930: activity.log file. %filters defines filters applied when parsing the
10931: log file. These can be start or end timestamps, or the type of action
10932: - log to look for Login or Logout events, check for Checkin or
10933: Checkout, role for role selection. The response is in the form
10934: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10935: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10936:
1.243 albertel 10937: =back
10938:
10939: =head2 User Roles
10940:
10941: =over 4
10942:
10943: =item *
10944:
1.810 raeburn 10945: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10946: F: full access
10947: U,I,K: authentication modes (cxx only)
10948: '': forbidden
10949: 1: user needs to choose course
10950: 2: browse allowed
1.766 albertel 10951: A: passphrase authentication needed
1.243 albertel 10952:
10953: =item *
10954:
10955: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10956: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10957: and course level
10958:
10959: =item *
10960:
1.988 raeburn 10961: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10962: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10963: $type is Course (default) or Community.
1.988 raeburn 10964: If $forcedefault evaluates to true, text returned will be default
10965: text for $type. Otherwise, if this is a course, the text returned
10966: will be a custom name for the role (if defined in the course's
10967: environment). If no custom name is defined the default is returned.
10968:
1.832 raeburn 10969: =item *
10970:
1.935 raeburn 10971: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10972: All arguments are optional. Returns a hash of a roles, either for
10973: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10974: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10975: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10976: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10977: For each key, value is set to colon-separated start and end times for
10978: the role. If no username and domain are specified, will default to
1.934 raeburn 10979: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10980: of role statuses (active, future or previous), roles
10981: (e.g., cc,in, st etc.) and domains of the roles which can be used
10982: to restrict the list of roles reported. If no array ref is
10983: provided for types, will default to return only active roles.
1.834 albertel 10984:
1.243 albertel 10985: =back
10986:
10987: =head2 User Modification
10988:
10989: =over 4
10990:
10991: =item *
10992:
1.957 raeburn 10993: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10994: user for the level given by URL. Optional start and end dates (leave empty
10995: string or zero for "no date")
1.191 harris41 10996:
10997: =item *
10998:
1.243 albertel 10999: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11000: change a users, password, possible return values are: ok,
11001: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11002: refused
1.191 harris41 11003:
11004: =item *
11005:
1.243 albertel 11006: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11007:
11008: =item *
11009:
1.1058 raeburn 11010: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11011: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11012:
11013: will update user information (firstname,middlename,lastname,generation,
11014: permanentemail), and if forceid is true, student/employee ID also.
11015: A user's institutional affiliation(s) can also be updated.
11016: User information fields will not be overwritten with empty entries
11017: unless the field is included in the $candelete array reference.
11018: This array is included when a single user is modified via "Manage Users",
11019: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11020:
11021: =item *
11022:
1.286 matthew 11023: modifystudent
11024:
1.957 raeburn 11025: modify a student's enrollment and identification information.
1.286 matthew 11026: The course id is resolved based on the current users environment.
11027: This means the envoking user must be a course coordinator or otherwise
11028: associated with a course.
11029:
1.297 matthew 11030: This call is essentially a wrapper for lonnet::modifyuser and
11031: lonnet::modify_student_enrollment
1.286 matthew 11032:
11033: Inputs:
11034:
11035: =over 4
11036:
1.957 raeburn 11037: =item B<$udom> Student's loncapa domain
1.286 matthew 11038:
1.957 raeburn 11039: =item B<$uname> Student's loncapa login name
1.286 matthew 11040:
1.964 bisitz 11041: =item B<$uid> Student/Employee ID
1.286 matthew 11042:
1.957 raeburn 11043: =item B<$umode> Student's authentication mode
1.286 matthew 11044:
1.957 raeburn 11045: =item B<$upass> Student's password
1.286 matthew 11046:
1.957 raeburn 11047: =item B<$first> Student's first name
1.286 matthew 11048:
1.957 raeburn 11049: =item B<$middle> Student's middle name
1.286 matthew 11050:
1.957 raeburn 11051: =item B<$last> Student's last name
1.286 matthew 11052:
1.957 raeburn 11053: =item B<$gene> Student's generation
1.286 matthew 11054:
1.957 raeburn 11055: =item B<$usec> Student's section in course
1.286 matthew 11056:
11057: =item B<$end> Unix time of the roles expiration
11058:
11059: =item B<$start> Unix time of the roles start date
11060:
11061: =item B<$forceid> If defined, allow $uid to be changed
11062:
11063: =item B<$desiredhome> server to use as home server for student
11064:
1.957 raeburn 11065: =item B<$email> Student's permanent e-mail address
11066:
11067: =item B<$type> Type of enrollment (auto or manual)
11068:
1.963 raeburn 11069: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11070:
11071: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11072:
1.963 raeburn 11073: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11074:
1.963 raeburn 11075: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11076:
1.963 raeburn 11077: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11078:
1.286 matthew 11079: =back
1.297 matthew 11080:
11081: =item *
11082:
11083: modify_student_enrollment
11084:
11085: Change a students enrollment status in a class. The environment variable
11086: 'role.request.course' must be defined for this function to proceed.
11087:
11088: Inputs:
11089:
11090: =over 4
11091:
11092: =item $udom, students domain
11093:
11094: =item $uname, students name
11095:
11096: =item $uid, students user id
11097:
11098: =item $first, students first name
11099:
11100: =item $middle
11101:
11102: =item $last
11103:
11104: =item $gene
11105:
11106: =item $usec
11107:
11108: =item $end
11109:
11110: =item $start
11111:
1.957 raeburn 11112: =item $type
11113:
11114: =item $locktype
11115:
11116: =item $cid
11117:
11118: =item $selfenroll
11119:
11120: =item $context
11121:
1.297 matthew 11122: =back
11123:
1.191 harris41 11124:
11125: =item *
11126:
1.243 albertel 11127: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11128: custom role; give a custom role to a user for the level given by URL. Specify
11129: name and domain of role author, and role name
1.191 harris41 11130:
11131: =item *
11132:
1.243 albertel 11133: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11134:
11135: =item *
11136:
1.243 albertel 11137: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11138:
11139: =back
11140:
11141: =head2 Course Infomation
11142:
11143: =over 4
1.191 harris41 11144:
11145: =item *
11146:
1.1118 foxr 11147: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11148: specified course id, including all environment settings for the
11149: course, the description of the course will be in the hash under the
11150: key 'description'
1.191 harris41 11151:
1.1118 foxr 11152: $options is an optional parameter that if supplied is a hash reference that controls
11153: what how this function works. It has the following key/values:
11154:
11155: =over 4
11156:
11157: =item freshen_cache
11158:
11159: If defined, and the environment cache for the course is valid, it is
11160: returned in the returned hash.
11161:
11162: =item one_time
11163:
11164: If defined, the last cache time is set to _now_
11165:
11166: =item user
11167:
11168: If defined, the supplied username is used instead of the current user.
11169:
11170:
11171: =back
11172:
1.191 harris41 11173: =item *
11174:
1.624 albertel 11175: resdata($name,$domain,$type,@which) : request for current parameter
11176: setting for a specific $type, where $type is either 'course' or 'user',
11177: @what should be a list of parameters to ask about. This routine caches
11178: answers for 5 minutes.
1.243 albertel 11179:
1.877 foxr 11180: =item *
11181:
11182: get_courseresdata($courseid, $domain) : dump the entire course resource
11183: data base, returning a hash that is keyed by the resource name and has
11184: values that are the resource value. I believe that the timestamps and
11185: versions are also returned.
11186:
11187:
1.243 albertel 11188: =back
11189:
11190: =head2 Course Modification
11191:
11192: =over 4
1.191 harris41 11193:
11194: =item *
11195:
1.243 albertel 11196: writecoursepref($courseid,%prefs) : write preferences (environment
11197: database) for a course
1.191 harris41 11198:
11199: =item *
11200:
1.1011 raeburn 11201: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11202:
11203: =item *
11204:
1.1038 raeburn 11205: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11206:
11207: =back
11208:
11209: =head2 Resource Subroutines
11210:
11211: =over 4
1.191 harris41 11212:
11213: =item *
11214:
1.243 albertel 11215: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11216:
11217: =item *
11218:
1.243 albertel 11219: repcopy($filename) : subscribes to the requested file, and attempts to
11220: replicate from the owning library server, Might return
1.607 raeburn 11221: 'unavailable', 'not_found', 'forbidden', 'ok', or
11222: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11223: resource. Expects the local filesystem pathname
11224: (/home/httpd/html/res/....)
11225:
11226: =back
11227:
11228: =head2 Resource Information
11229:
11230: =over 4
1.191 harris41 11231:
11232: =item *
11233:
1.243 albertel 11234: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11235: a vairety of different possible values, $varname should be a request
11236: string, and the other parameters can be used to specify who and what
11237: one is asking about.
11238:
11239: Possible values for $varname are environment.lastname (or other item
11240: from the envirnment hash), user.name (or someother aspect about the
11241: user), resource.0.maxtries (or some other part and parameter of a
11242: resource)
1.204 albertel 11243:
11244: =item *
11245:
1.243 albertel 11246: directcondval($number) : get current value of a condition; reads from a state
11247: string
1.204 albertel 11248:
11249: =item *
11250:
1.243 albertel 11251: condval($condidx) : value of condition index based on state
1.204 albertel 11252:
11253: =item *
11254:
1.243 albertel 11255: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11256: resource's metadata, $what should be either a specific key, or either
11257: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11258: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11259:
11260: this function automatically caches all requests
1.191 harris41 11261:
11262: =item *
11263:
1.243 albertel 11264: metadata_query($query,$custom,$customshow) : make a metadata query against the
11265: network of library servers; returns file handle of where SQL and regex results
11266: will be stored for query
1.191 harris41 11267:
11268: =item *
11269:
1.243 albertel 11270: symbread($filename) : return symbolic list entry (filename argument optional);
11271: returns the data handle
1.191 harris41 11272:
11273: =item *
11274:
1.243 albertel 11275: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11276: a possible symb for the URL in $thisfn, and if is an encryypted
11277: resource that the user accessed using /enc/ returns a 1 on success, 0
11278: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11279: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11280:
1.191 harris41 11281:
11282: =item *
11283:
1.243 albertel 11284: symbclean($symb) : removes versions numbers from a symb, returns the
11285: cleaned symb
1.191 harris41 11286:
11287: =item *
11288:
1.243 albertel 11289: is_on_map($uri) : checks if the $uri is somewhere on the current
11290: course map, user must be in a course for it to work.
1.191 harris41 11291:
11292: =item *
11293:
1.243 albertel 11294: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11295:
11296: =item *
11297:
1.243 albertel 11298: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11299: a random seed, all arguments are optional, if they aren't sent it uses the
11300: environment to derive them. Note: if symb isn't sent and it can't get one
11301: from &symbread it will use the current time as its return value
1.191 harris41 11302:
11303: =item *
11304:
1.243 albertel 11305: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11306: unfakeable, receipt
1.191 harris41 11307:
11308: =item *
11309:
1.620 albertel 11310: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11311:
11312: =item *
11313:
1.243 albertel 11314: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11315:
11316: =item *
11317:
1.243 albertel 11318: 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 11319:
11320: =item *
11321:
1.243 albertel 11322: 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 11323:
11324: =item *
11325:
1.243 albertel 11326: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11327:
11328: =item *
11329:
1.243 albertel 11330: devalidate($symb) : devalidate temporary spreadsheet calculations,
11331: forcing spreadsheet to reevaluate the resource scores next time.
11332:
11333: =back
11334:
11335: =head2 Storing/Retreiving Data
11336:
11337: =over 4
1.191 harris41 11338:
11339: =item *
11340:
1.243 albertel 11341: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11342: for this url; hashref needs to be given and should be a \%hashname; the
11343: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11344: be derived from the env
1.191 harris41 11345:
11346: =item *
11347:
1.243 albertel 11348: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11349: uses critical subroutine
1.191 harris41 11350:
11351: =item *
11352:
1.243 albertel 11353: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11354: all args are optional
1.191 harris41 11355:
11356: =item *
11357:
1.717 albertel 11358: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11359: dumps the complete (or key matching regexp) namespace into a hash
11360: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11361: normally &store()ed into
11362:
11363: $range should be either an integer '100' (give me the first 100
11364: matching records)
11365: or be two integers sperated by a - with no spaces
11366: '30-50' (give me the 30th through the 50th matching
11367: records)
11368:
11369:
11370: =item *
11371:
11372: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11373: replaces a &store() version of data with a replacement set of data
11374: for a particular resource in a namespace passed in the $storehash hash
11375: reference
11376:
11377: =item *
11378:
1.243 albertel 11379: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11380: works very similar to store/cstore, but all data is stored in a
11381: temporary location and can be reset using tmpreset, $storehash should
11382: be a hash reference, returns nothing on success
1.191 harris41 11383:
11384: =item *
11385:
1.243 albertel 11386: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11387: similar to restore, but all data is stored in a temporary location and
11388: can be reset using tmpreset. Returns a hash of values on success,
11389: error string otherwise.
1.191 harris41 11390:
11391: =item *
11392:
1.243 albertel 11393: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11394: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11395:
11396: =item *
11397:
1.243 albertel 11398: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11399: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11400:
11401: =item *
11402:
1.243 albertel 11403: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11404: namesp ($udom and $uname are optional)
1.191 harris41 11405:
11406: =item *
11407:
1.702 albertel 11408: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11409: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11410: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11411:
1.702 albertel 11412: $range should be either an integer '100' (give me the first 100
11413: matching records)
11414: or be two integers sperated by a - with no spaces
11415: '30-50' (give me the 30th through the 50th matching
11416: records)
1.449 matthew 11417: =item *
11418:
11419: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11420: $store can be a scalar, an array reference, or if the amount to be
11421: incremented is > 1, a hash reference.
11422:
11423: ($udom and $uname are optional)
1.191 harris41 11424:
11425: =item *
11426:
1.243 albertel 11427: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11428: ($udom and $uname are optional)
1.191 harris41 11429:
11430: =item *
11431:
1.243 albertel 11432: cput($namespace,$storehash,$udom,$uname) : critical put
11433: ($udom and $uname are optional)
1.191 harris41 11434:
11435: =item *
11436:
1.748 albertel 11437: newput($namespace,$storehash,$udom,$uname) :
11438:
11439: Attempts to store the items in the $storehash, but only if they don't
11440: currently exist, if this succeeds you can be certain that you have
11441: successfully created a new key value pair in the $namespace db.
11442:
11443:
11444: Args:
11445: $namespace: name of database to store values to
11446: $storehash: hashref to store to the db
11447: $udom: (optional) domain of user containing the db
11448: $uname: (optional) name of user caontaining the db
11449:
11450: Returns:
11451: 'ok' -> succeeded in storing all keys of $storehash
11452: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11453: least <key> already existed in the db (other
11454: requested keys may also already exist)
1.967 bisitz 11455: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11456: 'con_lost' -> unable to contact request server
11457: 'refused' -> action was not allowed by remote machine
11458:
11459:
11460: =item *
11461:
1.243 albertel 11462: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11463: reference filled in from namesp (encrypts the return communication)
11464: ($udom and $uname are optional)
1.191 harris41 11465:
11466: =item *
11467:
1.243 albertel 11468: log($udom,$name,$home,$message) : write to permanent log for user; use
11469: critical subroutine
11470:
1.806 raeburn 11471: =item *
11472:
1.860 raeburn 11473: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11474: array reference filled in from namespace found in domain level on either
11475: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11476:
11477: =item *
11478:
1.860 raeburn 11479: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11480: domain level either on specified domain server ($uhome) or primary domain
11481: server ($udom and $uhome are optional)
1.806 raeburn 11482:
1.943 raeburn 11483: =item *
11484:
11485: get_domain_defaults($target_domain) : returns hash with defaults for
11486: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11487: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11488: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11489: Values are retrieved from cache (if current), or from domain's configuration.db
11490: (if available), or lastly from values in lonTabs/dns_domain,tab,
11491: or lonTabs/domain.tab.
11492:
11493: %domdefaults = &get_auth_defaults($target_domain);
11494:
1.243 albertel 11495: =back
11496:
11497: =head2 Network Status Functions
11498:
11499: =over 4
1.191 harris41 11500:
11501: =item *
11502:
11503: dirlist($uri) : return directory list based on URI
11504:
11505: =item *
11506:
1.243 albertel 11507: spareserver() : find server with least workload from spare.tab
11508:
1.986 foxr 11509:
11510: =item *
11511:
11512: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11513: if there is no corresponding loncapa host.
11514:
1.243 albertel 11515: =back
11516:
1.986 foxr 11517:
1.243 albertel 11518: =head2 Apache Request
11519:
11520: =over 4
1.191 harris41 11521:
11522: =item *
11523:
1.243 albertel 11524: ssi($url,%hash) : server side include, does a complete request cycle on url to
11525: localhost, posts hash
11526:
11527: =back
11528:
11529: =head2 Data to String to Data
11530:
11531: =over 4
1.191 harris41 11532:
11533: =item *
11534:
1.243 albertel 11535: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11536: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11537:
11538: =item *
11539:
1.243 albertel 11540: hashref2str($hashref) : convert a hashref into a string complete with
11541: escaping and '=' and '&' separators, supports elements that are
11542: arrayrefs and hashrefs
1.191 harris41 11543:
11544: =item *
11545:
1.243 albertel 11546: arrayref2str($arrayref) : convert an arrayref into a string complete
11547: with escaping and '&' separators, supports elements that are arrayrefs
11548: and hashrefs
1.191 harris41 11549:
11550: =item *
11551:
1.243 albertel 11552: str2hash($string) : convert string to hash using unescaping and
11553: splitting on '=' and '&', supports elements that are arrayrefs and
11554: hashrefs
1.191 harris41 11555:
11556: =item *
11557:
1.243 albertel 11558: str2array($string) : convert string to hash using unescaping and
11559: splitting on '&', supports elements that are arrayrefs and hashrefs
11560:
11561: =back
11562:
11563: =head2 Logging Routines
11564:
11565:
11566: These routines allow one to make log messages in the lonnet.log and
11567: lonnet.perm logfiles.
1.191 harris41 11568:
1.1119 foxr 11569: =over 4
11570:
1.191 harris41 11571: =item *
11572:
1.243 albertel 11573: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11574:
11575: =item *
11576:
1.243 albertel 11577: logthis() : append message to the normal lonnet.log file, it gets
11578: preiodically rolled over and deleted.
1.191 harris41 11579:
11580: =item *
11581:
1.243 albertel 11582: logperm() : append a permanent message to lonnet.perm.log, this log
11583: file never gets deleted by any automated portion of the system, only
11584: messages of critical importance should go in here.
11585:
1.1119 foxr 11586:
1.243 albertel 11587: =back
11588:
11589: =head2 General File Helper Routines
11590:
11591: =over 4
1.191 harris41 11592:
11593: =item *
11594:
1.481 raeburn 11595: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11596: (a) files in /uploaded
11597: (i) If a local copy of the file exists -
11598: compares modification date of local copy with last-modified date for
11599: definitive version stored on home server for course. If local copy is
11600: stale, requests a new version from the home server and stores it.
11601: If the original has been removed from the home server, then local copy
11602: is unlinked.
11603: (ii) If local copy does not exist -
11604: requests the file from the home server and stores it.
11605:
11606: If $caller is 'uploadrep':
11607: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11608: for request for files originally uploaded via DOCS.
11609: - returns 'ok' if fresh local copy now available, -1 otherwise.
11610:
11611: Otherwise:
11612: This indicates a call from the content generation phase of the request.
11613: - returns the entire contents of the file or -1.
11614:
11615: (b) files in /res
11616: - returns the entire contents of a file or -1;
11617: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11618:
1.712 albertel 11619:
11620: =item *
11621:
11622: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11623: reference
11624:
11625: returns either a stat() list of data about the file or an empty list
11626: if the file doesn't exist or couldn't find out about it (connection
11627: problems or user unknown)
11628:
1.191 harris41 11629: =item *
11630:
1.243 albertel 11631: filelocation($dir,$file) : returns file system location of a file
11632: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11633: directory that relative $file lookups are to looked in ($dir of /a/dir
11634: and a file of ../bob will become /a/bob)
1.191 harris41 11635:
11636: =item *
11637:
11638: hreflocation($dir,$file) : returns file system location or a URL; same as
11639: filelocation except for hrefs
11640:
11641: =item *
11642:
11643: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11644:
1.243 albertel 11645: =back
11646:
1.608 albertel 11647: =head2 Usererfile file routines (/uploaded*)
11648:
11649: =over 4
11650:
11651: =item *
11652:
11653: userfileupload(): main rotine for putting a file in a user or course's
11654: filespace, arguments are,
11655:
1.620 albertel 11656: formname - required - this is the name of the element in $env where the
1.608 albertel 11657: filename, and the contents of the file to create/modifed exist
1.620 albertel 11658: the filename is in $env{'form.'.$formname.'.filename'} and the
11659: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11660: context - if coursedoc, store the file in the course of the active role
11661: of the current user;
11662: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11663: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11664: subdir - required - subdirectory to put the file in under ../userfiles/
11665: if undefined, it will be placed in "unknown"
11666:
11667: (This routine calls clean_filename() to remove any dangerous
11668: characters from the filename, and then calls finuserfileupload() to
11669: complete the transaction)
11670:
11671: returns either the url of the uploaded file (/uploaded/....) if successful
11672: and /adm/notfound.html if unsuccessful
11673:
11674: =item *
11675:
11676: clean_filename(): routine for cleaing a filename up for storage in
11677: userfile space, argument is:
11678:
11679: filename - proposed filename
11680:
11681: returns: the new clean filename
11682:
11683: =item *
11684:
1.1090 raeburn 11685: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11686: userspace, probably shouldn't be called directly
11687:
11688: docuname: username or courseid of destination for the file
11689: docudom: domain of user/course of destination for the file
11690: formname: same as for userfileupload()
1.1090 raeburn 11691: fname: filename (including subdirectories) for the file
11692: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11693: allfiles: reference to hash used to store objects found by parser
11694: codebase: reference to hash used for codebases of java objects found by parser
11695: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11696: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11697: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11698: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11699: context: if 'overwrite', will move the uploaded file from its temporary location to
11700: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 11701: mimetype: reference to scalar to accommodate mime type determined
11702: from File::MMagic if $parser = parse.
1.608 albertel 11703:
11704: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11705: and /adm/notfound.html if unsuccessful (or an error message if context
11706: was 'overwrite').
11707:
1.608 albertel 11708:
11709: =item *
11710:
11711: renameuserfile(): renames an existing userfile to a new name
11712:
11713: Args:
11714: docuname: username or courseid of destination for the file
11715: docudom: domain of user/course of destination for the file
11716: old: current file name (including any subdirs under userfiles)
11717: new: desired file name (including any subdirs under userfiles)
11718:
11719: =item *
11720:
11721: mkdiruserfile(): creates a directory is a userfiles dir
11722:
11723: Args:
11724: docuname: username or courseid of destination for the file
11725: docudom: domain of user/course of destination for the file
11726: dir: dir to create (including any subdirs under userfiles)
11727:
11728: =item *
11729:
11730: removeuserfile(): removes a file that exists in userfiles
11731:
11732: Args:
11733: docuname: username or courseid of destination for the file
11734: docudom: domain of user/course of destination for the file
11735: fname: filname to delete (including any subdirs under userfiles)
11736:
11737: =item *
11738:
11739: removeuploadedurl(): convience function for removeuserfile()
11740:
11741: Args:
11742: url: a full /uploaded/... url to delete
11743:
1.747 albertel 11744: =item *
11745:
11746: get_portfile_permissions():
11747: Args:
11748: domain: domain of user or course contain the portfolio files
11749: user: name of user or num of course contain the portfolio files
11750: Returns:
11751: hashref of a dump of the proper file_permissions.db
11752:
11753:
11754: =item *
11755:
11756: get_access_controls():
11757:
11758: Args:
11759: current_permissions: the hash ref returned from get_portfile_permissions()
11760: group: (optional) the group you want the files associated with
11761: file: (optional) the file you want access info on
11762:
11763: Returns:
1.749 raeburn 11764: a hash (keys are file names) of hashes containing
11765: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11766: values are XML containing access control settings (see below)
1.747 albertel 11767:
11768: Internal notes:
11769:
1.749 raeburn 11770: access controls are stored in file_permissions.db as key=value pairs.
11771: key -> path to file/file_name\0uniqueID:scope_end_start
11772: where scope -> public,guest,course,group,domains or users.
11773: end -> UNIX time for end of access (0 -> no end date)
11774: start -> UNIX time for start of access
11775:
11776: value -> XML description of access control
11777: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11778: <start></start>
11779: <end></end>
11780:
11781: <password></password> for scope type = guest
11782:
11783: <domain></domain> for scope type = course or group
11784: <number></number>
11785: <roles id="">
11786: <role></role>
11787: <access></access>
11788: <section></section>
11789: <group></group>
11790: </roles>
11791:
11792: <dom></dom> for scope type = domains
11793:
11794: <users> for scope type = users
11795: <user>
11796: <uname></uname>
11797: <udom></udom>
11798: </user>
11799: </users>
11800: </scope>
11801:
11802: Access data is also aggregated for each file in an additional key=value pair:
11803: key -> path to file/file_name\0accesscontrol
11804: value -> reference to hash
11805: hash contains key = value pairs
11806: where key = uniqueID:scope_end_start
11807: value = UNIX time record was last updated
11808:
11809: Used to improve speed of look-ups of access controls for each file.
11810:
11811: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11812:
11813: modify_access_controls():
11814:
11815: Modifies access controls for a portfolio file
11816: Args
11817: 1. file name
11818: 2. reference to hash of required changes,
11819: 3. domain
11820: 4. username
11821: where domain,username are the domain of the portfolio owner
11822: (either a user or a course)
11823:
11824: Returns:
11825: 1. result of additions or updates ('ok' or 'error', with error message).
11826: 2. result of deletions ('ok' or 'error', with error message).
11827: 3. reference to hash of any new or updated access controls.
11828: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11829: key = integer (inbound ID)
11830: value = uniqueID
1.747 albertel 11831:
1.608 albertel 11832: =back
11833:
1.243 albertel 11834: =head2 HTTP Helper Routines
11835:
11836: =over 4
11837:
1.191 harris41 11838: =item *
11839:
11840: escape() : unpack non-word characters into CGI-compatible hex codes
11841:
11842: =item *
11843:
11844: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11845:
1.243 albertel 11846: =back
11847:
11848: =head1 PRIVATE SUBROUTINES
11849:
11850: =head2 Underlying communication routines (Shouldn't call)
11851:
11852: =over 4
11853:
11854: =item *
11855:
11856: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11857:
11858: =item *
11859:
11860: reply() : uses subreply to send a message to remote machine, logs all failures
11861:
11862: =item *
11863:
11864: critical() : passes a critical message to another server; if cannot
11865: get through then place message in connection buffer directory and
11866: returns con_delayed, if incapable of saving message, returns
11867: con_failed
11868:
11869: =item *
11870:
11871: reconlonc() : tries to reconnect lonc client processes.
11872:
11873: =back
11874:
11875: =head2 Resource Access Logging
11876:
11877: =over 4
11878:
11879: =item *
11880:
11881: flushcourselogs() : flush (save) buffer logs and access logs
11882:
11883: =item *
11884:
11885: courselog($what) : save message for course in hash
11886:
11887: =item *
11888:
11889: courseacclog($what) : save message for course using &courselog(). Perform
11890: special processing for specific resource types (problems, exams, quizzes, etc).
11891:
1.191 harris41 11892: =item *
11893:
11894: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11895: as a PerlChildExitHandler
1.243 albertel 11896:
11897: =back
11898:
11899: =head2 Other
11900:
11901: =over 4
11902:
11903: =item *
11904:
11905: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11906:
11907: =back
11908:
11909: =cut
1.877 foxr 11910:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>