Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.63
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.63! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.62 2015/04/01 23:43:55 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.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 847: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
848: $try_server));
1.1123 raeburn 849: ($spare_server, $lowest_load) =
850: &compare_server_load($try_server, $spare_server, $lowest_load);
851: }
1.1083 raeburn 852: }
1.784 albertel 853:
1.1123 raeburn 854: my $found_server = ($spare_server ne '' && $lowest_load < 100);
855:
856: if (!$found_server) {
857: if (ref($spareshash->{'default'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,
860: $remotesessions,$try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
1.1172.2.41 raeburn 884: my ($try_server, $spare_server, $lowest_load, $required) = @_;
885:
886: if ($required) {
887: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
888: my $remoterev = &get_server_loncaparev(undef,$try_server);
889: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
890: if (($major eq '' && $minor eq '') ||
891: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
892: return ($spare_server,$lowest_load);
893: }
894: }
1.784 albertel 895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1172.2.47 raeburn 955: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1172.2.47 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
960: if ($skiploadbal) {
961: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
962: unless (defined($cached)) {
963: my $cachetime = 60*60*24;
964: my %domconfig =
965: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
966: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
967: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
968: $cachetime);
969: }
970: }
971: }
1.1076 raeburn 972: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 973: my $loginvia;
1.1172.2.47 raeburn 974: if ($skiploadbal) {
975: if (ref($balancers) eq 'HASH') {
976: next if (exists($balancers->{$lonhost}));
977: }
978: }
1.1115 raeburn 979: if ($checkloginvia) {
980: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 981: if ($loginvia) {
982: my ($server,$path) = split(/:/,$loginvia);
983: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 984: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 985: if ($login_host eq $server) {
986: $portal_path = $path;
1.1151 raeburn 987: $isredirect = 1;
1.1116 raeburn 988: }
989: } else {
990: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 992: if ($login_host eq $lonhost) {
993: $portal_path = '';
1.1151 raeburn 994: $isredirect = '';
1.1116 raeburn 995: }
996: }
997: } else {
1.1076 raeburn 998: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 999: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1000: }
1001: }
1002: if ($login_host ne '') {
1.1116 raeburn 1003: $hostname = &hostname($login_host);
1.1076 raeburn 1004: }
1.1151 raeburn 1005: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1006: }
1007:
1.202 matthew 1008: # --------------------------------------------- Try to change a user's password
1009:
1010: sub changepass {
1.799 raeburn 1011: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1012: $currentpass = &escape($currentpass);
1013: $newpass = &escape($newpass);
1.1030 raeburn 1014: my $lonhost = $perlvar{'lonHostID'};
1015: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1016: $server);
1017: if (! $answer) {
1018: &logthis("No reply on password change request to $server ".
1019: "by $uname in domain $udom.");
1020: } elsif ($answer =~ "^ok") {
1021: &logthis("$uname in $udom successfully changed their password ".
1022: "on $server.");
1023: } elsif ($answer =~ "^pwchange_failure") {
1024: &logthis("$uname in $udom was unable to change their password ".
1025: "on $server. The action was blocked by either lcpasswd ".
1026: "or pwchange");
1027: } elsif ($answer =~ "^non_authorized") {
1028: &logthis("$uname in $udom did not get their password correct when ".
1029: "attempting to change it on $server.");
1030: } elsif ($answer =~ "^auth_mode_error") {
1031: &logthis("$uname in $udom attempted to change their password despite ".
1032: "not being locally or internally authenticated on $server.");
1033: } elsif ($answer =~ "^unknown_user") {
1034: &logthis("$uname in $udom attempted to change their password ".
1035: "on $server but were unable to because $server is not ".
1036: "their home server.");
1037: } elsif ($answer =~ "^refused") {
1038: &logthis("$server refused to change $uname in $udom password because ".
1039: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1040: } elsif ($answer =~ "invalid_client") {
1041: &logthis("$server refused to change $uname in $udom password because ".
1042: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1043: }
1044: return $answer;
1.1 albertel 1045: }
1046:
1.169 harris41 1047: # ----------------------- Try to determine user's current authentication scheme
1048:
1049: sub queryauthenticate {
1050: my ($uname,$udom)=@_;
1.456 albertel 1051: my $uhome=&homeserver($uname,$udom);
1052: if (!$uhome) {
1053: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1054: return 'no_host';
1055: }
1056: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1057: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1059: }
1.456 albertel 1060: return $answer;
1.169 harris41 1061: }
1062:
1.1 albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1064:
1.1 albertel 1065: sub authenticate {
1.1073 raeburn 1066: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1067: $upass=&escape($upass);
1068: $uname= &LONCAPA::clean_username($uname);
1.836 www 1069: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1070: my $newhome;
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: # Maybe the machine was offline and only re-appeared again recently?
1073: &reconlonc();
1074: # One more
1.952 raeburn 1075: $uhome=&homeserver($uname,$udom,1);
1076: if (($uhome eq 'no_host') && $checkdefauth) {
1077: if (defined(&domain($udom,'primary'))) {
1078: $newhome=&domain($udom,'primary');
1079: }
1080: if ($newhome ne '') {
1081: $uhome = $newhome;
1082: }
1083: }
1.836 www 1084: if ((!$uhome) || ($uhome eq 'no_host')) {
1085: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1086: return 'no_host';
1087: }
1.1 albertel 1088: }
1.1073 raeburn 1089: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1090: if ($answer eq 'authorized') {
1.952 raeburn 1091: if ($newhome) {
1092: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1093: return 'no_account_on_host';
1094: } else {
1095: &logthis("User $uname at $udom authorized by $uhome");
1096: return $uhome;
1097: }
1.471 albertel 1098: }
1099: if ($answer eq 'non_authorized') {
1100: &logthis("User $uname at $udom rejected by $uhome");
1101: return 'no_host';
1.9 www 1102: }
1.471 albertel 1103: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1104: return 'no_host';
1105: }
1106:
1.1073 raeburn 1107: sub can_host_session {
1.1074 raeburn 1108: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1109: my $canhost = 1;
1.1074 raeburn 1110: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1111: if (ref($remotesessions) eq 'HASH') {
1112: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1113: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1114: $canhost = 0;
1115: } else {
1116: $canhost = 1;
1117: }
1118: }
1119: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1120: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1121: $canhost = 1;
1122: } else {
1123: $canhost = 0;
1124: }
1125: }
1126: if ($canhost) {
1127: if ($remotesessions->{'version'} ne '') {
1128: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1129: if ($reqmajor ne '' && $reqminor ne '') {
1130: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1131: my $major = $1;
1132: my $minor = $2;
1133: if (($major < $reqmajor ) ||
1134: (($major == $reqmajor) && ($minor < $reqminor))) {
1135: $canhost = 0;
1136: }
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: }
1144: if ($canhost) {
1145: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1146: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1147: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1148: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1151: $canhost = 0;
1152: } else {
1153: $canhost = 1;
1154: }
1155: }
1156: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1157: if (($uint_dom ne '') &&
1158: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1159: $canhost = 1;
1160: } else {
1161: $canhost = 0;
1162: }
1163: }
1164: }
1165: }
1166: return $canhost;
1167: }
1168:
1.1083 raeburn 1169: sub spare_can_host {
1170: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1171: my $canhost=1;
1.1172.2.62 raeburn 1172: my $try_server_hostname = &hostname($try_server);
1173: my $serverhomeID = &get_server_homeID($try_server_hostname);
1174: my $serverhomedom = &host_domain($serverhomeID);
1175: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1176: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1177: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1178: $canhost = 0;
1179: }
1180: }
1181: if (($canhost) && ($uint_dom)) {
1182: my @intdoms;
1183: my $internet_names = &get_internet_names($try_server);
1184: if (ref($internet_names) eq 'ARRAY') {
1185: @intdoms = @{$internet_names};
1186: }
1187: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1188: my $remoterev = &get_server_loncaparev(undef,$try_server);
1189: $canhost = &can_host_session($udom,$try_server,$remoterev,
1190: $remotesessions,
1191: $defdomdefaults{'hostedsessions'});
1192: }
1.1083 raeburn 1193: }
1194: return $canhost;
1195: }
1196:
1.1123 raeburn 1197: sub this_host_spares {
1198: my ($dom) = @_;
1.1126 raeburn 1199: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1200: my @hosts = ¤t_machine_ids();
1201: foreach my $lonhost (@hosts) {
1202: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1203: $dom_in_use = $dom;
1204: $lonhost_in_use = $lonhost;
1.1123 raeburn 1205: last;
1206: }
1207: }
1.1126 raeburn 1208: if ($dom_in_use ne '') {
1209: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1210: }
1211: if (ref($result) ne 'HASH') {
1212: $lonhost_in_use = $perlvar{'lonHostID'};
1213: $dom_in_use = &host_domain($lonhost_in_use);
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: if (ref($result) ne 'HASH') {
1216: $result = \%spareid;
1217: }
1218: }
1219: return $result;
1220: }
1221:
1222: sub spares_for_offload {
1223: my ($dom_in_use,$lonhost_in_use) = @_;
1224: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1225: if (defined($cached)) {
1226: return $result;
1227: } else {
1.1126 raeburn 1228: my $cachetime = 60*60*24;
1229: my %domconfig =
1230: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1231: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1232: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1234: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1235: }
1236: }
1237: }
1238: }
1.1126 raeburn 1239: return;
1.1123 raeburn 1240: }
1241:
1.1129 raeburn 1242: sub get_lonbalancer_config {
1243: my ($servers) = @_;
1244: my ($currbalancer,$currtargets);
1245: if (ref($servers) eq 'HASH') {
1246: foreach my $server (keys(%{$servers})) {
1247: my %what = (
1248: spareid => 1,
1249: perlvar => 1,
1250: );
1251: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1252: if ($result eq 'ok') {
1253: if (ref($returnhash) eq 'HASH') {
1254: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1255: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1256: $currbalancer = $server;
1257: $currtargets = {};
1258: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1259: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1260: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1261: }
1262: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1263: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1264: }
1265: }
1266: last;
1267: }
1268: }
1269: }
1270: }
1271: }
1272: }
1273: return ($currbalancer,$currtargets);
1274: }
1275:
1276: sub check_loadbalancing {
1277: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1278: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1279: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1280: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1281: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1282: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1283: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1284: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1285: my $serverhomedom = &host_domain($lonhost);
1286:
1287: my $cachetime = 60*60*24;
1288:
1289: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1290: $dom_in_use = $udom;
1291: $homeintdom = 1;
1292: } else {
1293: $dom_in_use = $serverhomedom;
1294: }
1295: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1296: unless (defined($cached)) {
1297: my %domconfig =
1298: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1299: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1300: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1301: }
1302: }
1303: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1304: ($is_balancer,$currtargets,$currrules) =
1305: &check_balancer_result($result,@hosts);
1.1129 raeburn 1306: if ($is_balancer) {
1307: if (ref($currrules) eq 'HASH') {
1308: if ($homeintdom) {
1309: if ($uname ne '') {
1310: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1311: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1312: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1313: $rule_in_effect = $currrules->{'_LC_author'};
1314: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1315: $rule_in_effect = $currrules->{'_LC_adv'}
1316: }
1317: }
1318: if ($rule_in_effect eq '') {
1319: my %userenv = &userenvironment($udom,$uname,'inststatus');
1320: if ($userenv{'inststatus'} ne '') {
1321: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1322: my ($othertitle,$usertypes,$types) =
1323: &Apache::loncommon::sorted_inst_types($udom);
1324: if (ref($types) eq 'ARRAY') {
1325: foreach my $type (@{$types}) {
1326: if (grep(/^\Q$type\E$/,@statuses)) {
1327: if (exists($currrules->{$type})) {
1328: $rule_in_effect = $currrules->{$type};
1329: }
1330: }
1331: }
1332: }
1333: } else {
1334: if (exists($currrules->{'default'})) {
1335: $rule_in_effect = $currrules->{'default'};
1336: }
1337: }
1338: }
1339: } else {
1340: if (exists($currrules->{'default'})) {
1341: $rule_in_effect = $currrules->{'default'};
1342: }
1343: }
1344: } else {
1345: if ($currrules->{'_LC_external'} ne '') {
1346: $rule_in_effect = $currrules->{'_LC_external'};
1347: }
1348: }
1349: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1350: $uname,$udom);
1351: }
1352: }
1353: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1354: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1355: unless (defined($cached)) {
1356: my %domconfig =
1357: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1358: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1359: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1360: }
1361: }
1362: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1363: ($is_balancer,$currtargets,$currrules) =
1364: &check_balancer_result($result,@hosts);
1365: if ($is_balancer) {
1.1129 raeburn 1366: if (ref($currrules) eq 'HASH') {
1367: if ($currrules->{'_LC_internetdom'} ne '') {
1368: $rule_in_effect = $currrules->{'_LC_internetdom'};
1369: }
1370: }
1371: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1372: $uname,$udom);
1373: }
1374: } else {
1375: if ($perlvar{'lonBalancer'} eq 'yes') {
1376: $is_balancer = 1;
1377: $offloadto = &this_host_spares($dom_in_use);
1378: }
1379: }
1380: } else {
1381: if ($perlvar{'lonBalancer'} eq 'yes') {
1382: $is_balancer = 1;
1383: $offloadto = &this_host_spares($dom_in_use);
1384: }
1385: }
1.1172.2.5 raeburn 1386: if ($is_balancer) {
1387: my $lowest_load = 30000;
1388: if (ref($offloadto) eq 'HASH') {
1389: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1390: foreach my $try_server (@{$offloadto->{'primary'}}) {
1391: ($otherserver,$lowest_load) =
1392: &compare_server_load($try_server,$otherserver,$lowest_load);
1393: }
1.1129 raeburn 1394: }
1.1172.2.5 raeburn 1395: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1396:
1.1172.2.5 raeburn 1397: if (!$found_server) {
1398: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1399: foreach my $try_server (@{$offloadto->{'default'}}) {
1400: ($otherserver,$lowest_load) =
1401: &compare_server_load($try_server,$otherserver,$lowest_load);
1402: }
1403: }
1404: }
1405: } elsif (ref($offloadto) eq 'ARRAY') {
1406: if (@{$offloadto} == 1) {
1407: $otherserver = $offloadto->[0];
1408: } elsif (@{$offloadto} > 1) {
1409: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1410: ($otherserver,$lowest_load) =
1411: &compare_server_load($try_server,$otherserver,$lowest_load);
1412: }
1413: }
1414: }
1.1172.2.5 raeburn 1415: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1416: $is_balancer = 0;
1417: if ($uname ne '' && $udom ne '') {
1418: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1419:
1420: &appenv({'user.loadbalexempt' => $lonhost,
1421: 'user.loadbalcheck.time' => time});
1422: }
1.1129 raeburn 1423: }
1424: }
1425: }
1426: return ($is_balancer,$otherserver);
1427: }
1428:
1.1172.2.12 raeburn 1429: sub check_balancer_result {
1430: my ($result,@hosts) = @_;
1431: my ($is_balancer,$currtargets,$currrules);
1432: if (ref($result) eq 'HASH') {
1433: if ($result->{'lonhost'} ne '') {
1434: my $currbalancer = $result->{'lonhost'};
1435: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1436: $is_balancer = 1;
1437: $currtargets = $result->{'targets'};
1438: $currrules = $result->{'rules'};
1439: }
1440: } else {
1441: foreach my $key (keys(%{$result})) {
1442: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1443: (ref($result->{$key}) eq 'HASH')) {
1444: $is_balancer = 1;
1445: $currrules = $result->{$key}{'rules'};
1446: $currtargets = $result->{$key}{'targets'};
1447: last;
1448: }
1449: }
1450: }
1451: }
1452: return ($is_balancer,$currtargets,$currrules);
1453: }
1454:
1.1129 raeburn 1455: sub get_loadbalancer_targets {
1456: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1457: my $offloadto;
1.1172.2.4 raeburn 1458: if ($rule_in_effect eq 'none') {
1459: return [$perlvar{'lonHostID'}];
1460: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1461: $offloadto = $currtargets;
1462: } else {
1463: if ($rule_in_effect eq 'homeserver') {
1464: my $homeserver = &homeserver($uname,$udom);
1465: if ($homeserver ne 'no_host') {
1466: $offloadto = [$homeserver];
1467: }
1468: } elsif ($rule_in_effect eq 'externalbalancer') {
1469: my %domconfig =
1470: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1471: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1472: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1473: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1474: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1475: }
1476: }
1477: } else {
1.1172.2.7 raeburn 1478: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1479: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1480: if (&hostname($remotebalancer) ne '') {
1481: $offloadto = [$remotebalancer];
1482: }
1483: }
1484: } elsif (&hostname($rule_in_effect) ne '') {
1485: $offloadto = [$rule_in_effect];
1486: }
1487: }
1488: return $offloadto;
1489: }
1490:
1.1127 raeburn 1491: sub internet_dom_servers {
1492: my ($dom) = @_;
1493: my (%uniqservers,%servers);
1494: my $primaryserver = &hostname(&domain($dom,'primary'));
1495: my @machinedoms = &machine_domains($primaryserver);
1496: foreach my $mdom (@machinedoms) {
1497: my %currservers = %servers;
1498: my %server = &get_servers($mdom);
1499: %servers = (%currservers,%server);
1500: }
1501: my %by_hostname;
1502: foreach my $id (keys(%servers)) {
1503: push(@{$by_hostname{$servers{$id}}},$id);
1504: }
1505: foreach my $hostname (sort(keys(%by_hostname))) {
1506: if (@{$by_hostname{$hostname}} > 1) {
1507: my $match = 0;
1508: foreach my $id (@{$by_hostname{$hostname}}) {
1509: if (&host_domain($id) eq $dom) {
1510: $uniqservers{$id} = $hostname;
1511: $match = 1;
1512: }
1513: }
1514: unless ($match) {
1515: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1516: }
1517: } else {
1518: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1519: }
1520: }
1521: return %uniqservers;
1522: }
1523:
1.1 albertel 1524: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1525:
1.599 albertel 1526: my %homecache;
1.1 albertel 1527: sub homeserver {
1.230 stredwic 1528: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1529: my $index="$uname:$udom";
1.426 albertel 1530:
1.599 albertel 1531: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1532:
1533: my %servers = &get_servers($udom,'library');
1534: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1535: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1536: exists($badServerCache{$tryserver}));
1.841 albertel 1537:
1538: my $answer=reply("home:$udom:$uname",$tryserver);
1539: if ($answer eq 'found') {
1540: delete($badServerCache{$tryserver});
1541: return $homecache{$index}=$tryserver;
1542: } elsif ($answer eq 'no_host') {
1543: $badServerCache{$tryserver}=1;
1544: }
1.1 albertel 1545: }
1546: return 'no_host';
1.70 www 1547: }
1548:
1549: # ------------------------------------- Find the usernames behind a list of IDs
1550:
1551: sub idget {
1552: my ($udom,@ids)=@_;
1553: my %returnhash=();
1554:
1.841 albertel 1555: my %servers = &get_servers($udom,'library');
1556: foreach my $tryserver (keys(%servers)) {
1557: my $idlist=join('&',@ids);
1558: $idlist=~tr/A-Z/a-z/;
1559: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1560: my @answer=();
1561: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1562: @answer=split(/\&/,$reply);
1563: } ;
1564: my $i;
1565: for ($i=0;$i<=$#ids;$i++) {
1566: if ($answer[$i]) {
1567: $returnhash{$ids[$i]}=$answer[$i];
1568: }
1569: }
1570: }
1.70 www 1571: return %returnhash;
1572: }
1573:
1574: # ------------------------------------- Find the IDs behind a list of usernames
1575:
1576: sub idrget {
1577: my ($udom,@unames)=@_;
1578: my %returnhash=();
1.800 albertel 1579: foreach my $uname (@unames) {
1580: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1581: }
1.70 www 1582: return %returnhash;
1583: }
1584:
1585: # ------------------------------- Store away a list of names and associated IDs
1586:
1587: sub idput {
1588: my ($udom,%ids)=@_;
1589: my %servers=();
1.800 albertel 1590: foreach my $uname (keys(%ids)) {
1591: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1592: my $uhom=&homeserver($uname,$udom);
1.70 www 1593: if ($uhom ne 'no_host') {
1.800 albertel 1594: my $id=&escape($ids{$uname});
1.70 www 1595: $id=~tr/A-Z/a-z/;
1.800 albertel 1596: my $esc_unam=&escape($uname);
1.70 www 1597: if ($servers{$uhom}) {
1.800 albertel 1598: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1599: } else {
1.800 albertel 1600: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1601: }
1602: }
1.191 harris41 1603: }
1.800 albertel 1604: foreach my $server (keys(%servers)) {
1605: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1606: }
1.344 www 1607: }
1608:
1.1172.2.30 raeburn 1609: # ---------------------------------------- Delete unwanted IDs from ids.db file
1610:
1611: sub iddel {
1612: my ($udom,$idshashref,$uhome)=@_;
1613: my %result=();
1614: unless (ref($idshashref) eq 'HASH') {
1615: return %result;
1616: }
1617: my %servers=();
1618: while (my ($id,$uname) = each(%{$idshashref})) {
1619: my $uhom;
1620: if ($uhome) {
1621: $uhom = $uhome;
1622: } else {
1623: $uhom=&homeserver($uname,$udom);
1624: }
1625: if ($uhom ne 'no_host') {
1626: if ($servers{$uhom}) {
1627: $servers{$uhom}.='&'.&escape($id);
1628: } else {
1629: $servers{$uhom}=&escape($id);
1630: }
1631: }
1632: }
1633: foreach my $server (keys(%servers)) {
1634: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1635: }
1636: return %result;
1637: }
1638:
1.1023 raeburn 1639: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1640: sub dump_dom {
1.1165 droeschl 1641: my ($namespace, $udom, $regexp) = @_;
1642:
1643: $udom ||= $env{'user.domain'};
1644:
1645: return () unless $udom;
1646:
1647: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1648: }
1649:
1.1023 raeburn 1650: # ------------------------------------------ get items from domain db files
1.806 raeburn 1651:
1652: sub get_dom {
1.860 raeburn 1653: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1654: return if ($udom eq 'public');
1.806 raeburn 1655: my $items='';
1656: foreach my $item (@$storearr) {
1657: $items.=&escape($item).'&';
1658: }
1659: $items=~s/\&$//;
1.860 raeburn 1660: if (!$udom) {
1661: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1662: return if ($udom eq 'public');
1.860 raeburn 1663: if (defined(&domain($udom,'primary'))) {
1664: $uhome=&domain($udom,'primary');
1665: } else {
1.874 albertel 1666: undef($uhome);
1.860 raeburn 1667: }
1668: } else {
1669: if (!$uhome) {
1670: if (defined(&domain($udom,'primary'))) {
1671: $uhome=&domain($udom,'primary');
1672: }
1673: }
1674: }
1675: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1676: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1677: my %returnhash;
1.875 albertel 1678: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1679: return %returnhash;
1680: }
1.806 raeburn 1681: my @pairs=split(/\&/,$rep);
1682: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1683: return @pairs;
1684: }
1685: my $i=0;
1686: foreach my $item (@$storearr) {
1687: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1688: $i++;
1689: }
1690: return %returnhash;
1691: } else {
1.880 banghart 1692: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1693: }
1694: }
1695:
1696: # -------------------------------------------- put items in domain db files
1697:
1698: sub put_dom {
1.860 raeburn 1699: my ($namespace,$storehash,$udom,$uhome)=@_;
1700: if (!$udom) {
1701: $udom=$env{'user.domain'};
1702: if (defined(&domain($udom,'primary'))) {
1703: $uhome=&domain($udom,'primary');
1704: } else {
1.874 albertel 1705: undef($uhome);
1.860 raeburn 1706: }
1707: } else {
1708: if (!$uhome) {
1709: if (defined(&domain($udom,'primary'))) {
1710: $uhome=&domain($udom,'primary');
1711: }
1712: }
1713: }
1714: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1715: my $items='';
1716: foreach my $item (keys(%$storehash)) {
1717: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1718: }
1719: $items=~s/\&$//;
1720: return &reply("putdom:$udom:$namespace:$items",$uhome);
1721: } else {
1.860 raeburn 1722: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1723: }
1724: }
1725:
1.1023 raeburn 1726: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1727: sub newput_dom {
1.1023 raeburn 1728: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1729: my $result;
1730: if (!$udom) {
1731: $udom=$env{'user.domain'};
1732: }
1.1023 raeburn 1733: if ($udom) {
1734: my $uname = &get_domainconfiguser($udom);
1735: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1736: }
1737: return $result;
1738: }
1739:
1.1023 raeburn 1740: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1741: sub del_dom {
1.1023 raeburn 1742: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1743: if (ref($storearr) eq 'ARRAY') {
1744: if (!$udom) {
1745: $udom=$env{'user.domain'};
1746: }
1.1023 raeburn 1747: if ($udom) {
1748: my $uname = &get_domainconfiguser($udom);
1749: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1750: }
1751: }
1752: }
1753:
1.1023 raeburn 1754: # ----------------------------------construct domainconfig user for a domain
1755: sub get_domainconfiguser {
1756: my ($udom) = @_;
1757: return $udom.'-domainconfig';
1758: }
1759:
1.837 raeburn 1760: sub retrieve_inst_usertypes {
1761: my ($udom) = @_;
1762: my (%returnhash,@order);
1.989 raeburn 1763: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1764: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1765: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1766: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1767: } else {
1768: if (defined(&domain($udom,'primary'))) {
1769: my $uhome=&domain($udom,'primary');
1770: my $rep=&reply("inst_usertypes:$udom",$uhome);
1771: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1772: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1773: return (\%returnhash,\@order);
1774: }
1775: my ($hashitems,$orderitems) = split(/:/,$rep);
1776: my @pairs=split(/\&/,$hashitems);
1777: foreach my $item (@pairs) {
1778: my ($key,$value)=split(/=/,$item,2);
1779: $key = &unescape($key);
1780: next if ($key =~ /^error: 2 /);
1781: $returnhash{$key}=&thaw_unescape($value);
1782: }
1783: my @esc_order = split(/\&/,$orderitems);
1784: foreach my $item (@esc_order) {
1785: push(@order,&unescape($item));
1786: }
1787: } else {
1.1172.2.44 raeburn 1788: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1789: }
1.1172.2.44 raeburn 1790: return (\%returnhash,\@order);
1.837 raeburn 1791: }
1792: }
1793:
1.868 raeburn 1794: sub is_domainimage {
1795: my ($url) = @_;
1796: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1797: if (&domain($1) ne '') {
1798: return '1';
1799: }
1800: }
1801: return;
1802: }
1803:
1.899 raeburn 1804: sub inst_directory_query {
1805: my ($srch) = @_;
1806: my $udom = $srch->{'srchdomain'};
1807: my %results;
1808: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1809: my $outcome;
1.899 raeburn 1810: if ($homeserver ne '') {
1.904 albertel 1811: my $queryid=&reply("querysend:instdirsearch:".
1812: &escape($srch->{'srchby'}).':'.
1813: &escape($srch->{'srchterm'}).':'.
1814: &escape($srch->{'srchtype'}),$homeserver);
1815: my $host=&hostname($homeserver);
1816: if ($queryid !~/^\Q$host\E\_/) {
1817: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1818: return;
1819: }
1820: my $response = &get_query_reply($queryid);
1821: my $maxtries = 5;
1822: my $tries = 1;
1823: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1824: $response = &get_query_reply($queryid);
1825: $tries ++;
1826: }
1827:
1828: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1829: if ($response eq 'unavailable') {
1830: $outcome = $response;
1831: } else {
1832: $outcome = 'ok';
1833: my @matches = split(/\n/,$response);
1834: foreach my $match (@matches) {
1835: my ($key,$value) = split(/=/,$match);
1836: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1837: }
1.899 raeburn 1838: }
1839: }
1840: }
1.909 raeburn 1841: return ($outcome,%results);
1.899 raeburn 1842: }
1843:
1844: sub usersearch {
1845: my ($srch) = @_;
1846: my $dom = $srch->{'srchdomain'};
1847: my %results;
1848: my %libserv = &all_library();
1849: my $query = 'usersearch';
1850: foreach my $tryserver (keys(%libserv)) {
1851: if (&host_domain($tryserver) eq $dom) {
1852: my $host=&hostname($tryserver);
1853: my $queryid=
1.911 raeburn 1854: &reply("querysend:".&escape($query).':'.
1855: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1856: &escape($srch->{'srchtype'}).':'.
1857: &escape($srch->{'srchterm'}),$tryserver);
1858: if ($queryid !~/^\Q$host\E\_/) {
1859: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1860: next;
1.899 raeburn 1861: }
1862: my $reply = &get_query_reply($queryid);
1863: my $maxtries = 1;
1864: my $tries = 1;
1865: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1866: $reply = &get_query_reply($queryid);
1867: $tries ++;
1868: }
1869: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1870: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1871: } else {
1.911 raeburn 1872: my @matches;
1873: if ($reply =~ /\n/) {
1874: @matches = split(/\n/,$reply);
1875: } else {
1876: @matches = split(/\&/,$reply);
1877: }
1.899 raeburn 1878: foreach my $match (@matches) {
1879: my ($uname,$udom,%userhash);
1.911 raeburn 1880: foreach my $entry (split(/:/,$match)) {
1881: my ($key,$value) =
1882: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1883: $userhash{$key} = $value;
1884: if ($key eq 'username') {
1885: $uname = $value;
1886: } elsif ($key eq 'domain') {
1887: $udom = $value;
1.911 raeburn 1888: }
1.899 raeburn 1889: }
1890: $results{$uname.':'.$udom} = \%userhash;
1891: }
1892: }
1893: }
1894: }
1895: return %results;
1896: }
1897:
1.912 raeburn 1898: sub get_instuser {
1899: my ($udom,$uname,$id) = @_;
1900: my $homeserver = &domain($udom,'primary');
1901: my ($outcome,%results);
1902: if ($homeserver ne '') {
1903: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1904: &escape($id).':'.&escape($udom),$homeserver);
1905: my $host=&hostname($homeserver);
1906: if ($queryid !~/^\Q$host\E\_/) {
1907: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1908: return;
1909: }
1910: my $response = &get_query_reply($queryid);
1911: my $maxtries = 5;
1912: my $tries = 1;
1913: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1914: $response = &get_query_reply($queryid);
1915: $tries ++;
1916: }
1917: if (!&error($response) && $response ne 'refused') {
1918: if ($response eq 'unavailable') {
1919: $outcome = $response;
1920: } else {
1921: $outcome = 'ok';
1922: my @matches = split(/\n/,$response);
1923: foreach my $match (@matches) {
1924: my ($key,$value) = split(/=/,$match);
1925: $results{&unescape($key)} = &thaw_unescape($value);
1926: }
1927: }
1928: }
1929: }
1930: my %userinfo;
1931: if (ref($results{$uname}) eq 'HASH') {
1932: %userinfo = %{$results{$uname}};
1933: }
1934: return ($outcome,%userinfo);
1935: }
1936:
1937: sub inst_rulecheck {
1.923 raeburn 1938: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1939: my %returnhash;
1940: if ($udom ne '') {
1941: if (ref($rules) eq 'ARRAY') {
1942: @{$rules} = map {&escape($_);} (@{$rules});
1943: my $rulestr = join(':',@{$rules});
1944: my $homeserver=&domain($udom,'primary');
1945: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1946: my $response;
1947: if ($item eq 'username') {
1948: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1949: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1950: $homeserver));
1.923 raeburn 1951: } elsif ($item eq 'id') {
1952: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1953: ':'.&escape($id).':'.$rulestr,
1954: $homeserver));
1.945 raeburn 1955: } elsif ($item eq 'selfcreate') {
1956: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1957: &escape($udom).':'.&escape($uname).
1958: ':'.$rulestr,$homeserver));
1.923 raeburn 1959: }
1.912 raeburn 1960: if ($response ne 'refused') {
1961: my @pairs=split(/\&/,$response);
1962: foreach my $item (@pairs) {
1963: my ($key,$value)=split(/=/,$item,2);
1964: $key = &unescape($key);
1965: next if ($key =~ /^error: 2 /);
1966: $returnhash{$key}=&thaw_unescape($value);
1967: }
1968: }
1969: }
1970: }
1971: }
1972: return %returnhash;
1973: }
1974:
1975: sub inst_userrules {
1.923 raeburn 1976: my ($udom,$check) = @_;
1.912 raeburn 1977: my (%ruleshash,@ruleorder);
1978: if ($udom ne '') {
1979: my $homeserver=&domain($udom,'primary');
1980: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1981: my $response;
1982: if ($check eq 'id') {
1983: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1984: $homeserver);
1.943 raeburn 1985: } elsif ($check eq 'email') {
1986: $response=&reply('instemailrules:'.&escape($udom),
1987: $homeserver);
1.923 raeburn 1988: } else {
1989: $response=&reply('instuserrules:'.&escape($udom),
1990: $homeserver);
1991: }
1.912 raeburn 1992: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1993: ($response ne 'unknown_cmd') &&
1.912 raeburn 1994: ($response ne 'no_such_host')) {
1995: my ($hashitems,$orderitems) = split(/:/,$response);
1996: my @pairs=split(/\&/,$hashitems);
1997: foreach my $item (@pairs) {
1998: my ($key,$value)=split(/=/,$item,2);
1999: $key = &unescape($key);
2000: next if ($key =~ /^error: 2 /);
2001: $ruleshash{$key}=&thaw_unescape($value);
2002: }
2003: my @esc_order = split(/\&/,$orderitems);
2004: foreach my $item (@esc_order) {
2005: push(@ruleorder,&unescape($item));
2006: }
2007: }
2008: }
2009: }
2010: return (\%ruleshash,\@ruleorder);
2011: }
2012:
1.976 raeburn 2013: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2014:
2015: sub get_domain_defaults {
1.1172.2.35 raeburn 2016: my ($domain,$ignore_cache) = @_;
2017: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2018: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2019: unless ($ignore_cache) {
2020: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2021: if (defined($cached)) {
2022: if (ref($result) eq 'HASH') {
2023: return %{$result};
2024: }
1.943 raeburn 2025: }
2026: }
2027: my %domdefaults;
2028: my %domconfig =
1.989 raeburn 2029: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2030: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2031: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2032: 'requestauthor','selfenrollment',
2033: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2034: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2035: if (ref($domconfig{'defaults'}) eq 'HASH') {
2036: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2037: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2038: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2039: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2040: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2041: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2042: } else {
2043: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2044: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2045: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2046: }
1.976 raeburn 2047: if (ref($domconfig{'quotas'}) eq 'HASH') {
2048: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2049: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2050: } else {
2051: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2052: }
1.1172.2.6 raeburn 2053: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2054: foreach my $item (@usertools) {
2055: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2056: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2057: }
2058: }
1.1172.2.29 raeburn 2059: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2060: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2061: }
1.976 raeburn 2062: }
1.985 raeburn 2063: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2064: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2065: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2066: }
2067: }
1.1172.2.9 raeburn 2068: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2069: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2070: }
1.989 raeburn 2071: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2072: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2073: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2074: }
2075: }
1.1047 raeburn 2076: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2077: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2078: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2079: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2080: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2081: }
1.1172.2.41 raeburn 2082: foreach my $type (@coursetypes) {
2083: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2084: unless ($type eq 'community') {
2085: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2086: }
2087: }
2088: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2089: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2090: }
1.1172.2.60 raeburn 2091: if ($domdefaults{'postsubmit'} eq 'on') {
2092: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2093: $domdefaults{$type.'postsubtimeout'} =
2094: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2095: }
2096: }
1.1172.2.30 raeburn 2097: }
1.1047 raeburn 2098: }
1.1073 raeburn 2099: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2100: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2101: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2102: }
2103: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2104: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2105: }
1.1172.2.62 raeburn 2106: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2107: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2108: }
1.1073 raeburn 2109: }
1.1172.2.41 raeburn 2110: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2111: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2112: my @settings = ('types','registered','enroll_dates','access_dates','section',
2113: 'approval','limit');
2114: foreach my $type (@coursetypes) {
2115: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2116: my @mgrdc = ();
2117: foreach my $item (@settings) {
2118: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2119: push(@mgrdc,$item);
2120: }
2121: }
2122: if (@mgrdc) {
2123: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2124: }
2125: }
2126: }
2127: }
2128: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2129: foreach my $type (@coursetypes) {
2130: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2131: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2132: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2133: }
2134: }
2135: }
2136: }
2137: }
1.1172.2.46 raeburn 2138: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2139: $domdefaults{'catauth'} = 'std';
2140: $domdefaults{'catunauth'} = 'std';
2141: if ($domconfig{'coursecategories'}{'auth'}) {
2142: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2143: }
2144: if ($domconfig{'coursecategories'}{'unauth'}) {
2145: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2146: }
2147: }
1.1172.2.23 raeburn 2148: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2149: return %domdefaults;
2150: }
2151:
1.344 www 2152: # --------------------------------------------------- Assign a key to a student
2153:
2154: sub assign_access_key {
1.364 www 2155: #
2156: # a valid key looks like uname:udom#comments
2157: # comments are being appended
2158: #
1.498 www 2159: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2160: $kdom=
1.620 albertel 2161: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2162: $knum=
1.620 albertel 2163: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2164: $cdom=
1.620 albertel 2165: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2166: $cnum=
1.620 albertel 2167: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2168: $udom=$env{'user.name'} unless (defined($udom));
2169: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2170: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2171: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2172: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2173: # assigned to this person
2174: # - this should not happen,
1.345 www 2175: # unless something went wrong
2176: # the first time around
2177: # ready to assign
1.364 www 2178: $logentry=$1.'; '.$logentry;
1.496 www 2179: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2180: $kdom,$knum) eq 'ok') {
1.345 www 2181: # key now belongs to user
1.346 www 2182: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2183: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2184: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2185: return 'ok';
2186: } else {
2187: return
2188: 'error: Count not permanently assign key, will need to be re-entered later.';
2189: }
2190: } else {
2191: return 'error: Could not assign key, try again later.';
2192: }
1.364 www 2193: } elsif (!$existing{$ckey}) {
1.345 www 2194: # the key does not exist
2195: return 'error: The key does not exist';
2196: } else {
2197: # the key is somebody else's
2198: return 'error: The key is already in use';
2199: }
1.344 www 2200: }
2201:
1.364 www 2202: # ------------------------------------------ put an additional comment on a key
2203:
2204: sub comment_access_key {
2205: #
2206: # a valid key looks like uname:udom#comments
2207: # comments are being appended
2208: #
2209: my ($ckey,$cdom,$cnum,$logentry)=@_;
2210: $cdom=
1.620 albertel 2211: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2212: $cnum=
1.620 albertel 2213: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2214: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2215: if ($existing{$ckey}) {
2216: $existing{$ckey}.='; '.$logentry;
2217: # ready to assign
1.367 www 2218: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2219: $cdom,$cnum) eq 'ok') {
2220: return 'ok';
2221: } else {
2222: return 'error: Count not store comment.';
2223: }
2224: } else {
2225: # the key does not exist
2226: return 'error: The key does not exist';
2227: }
2228: }
2229:
1.344 www 2230: # ------------------------------------------------------ Generate a set of keys
2231:
2232: sub generate_access_keys {
1.364 www 2233: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2234: $cdom=
1.620 albertel 2235: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2236: $cnum=
1.620 albertel 2237: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2238: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2239: unless (($cdom) && ($cnum)) { return 0; }
2240: if ($number>10000) { return 0; }
2241: sleep(2); # make sure don't get same seed twice
2242: srand(time()^($$+($$<<15))); # from "Programming Perl"
2243: my $total=0;
2244: for (my $i=1;$i<=$number;$i++) {
2245: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2246: sprintf("%lx",int(100000*rand)).'-'.
2247: sprintf("%lx",int(100000*rand));
2248: $newkey=~s/1/g/g; # folks mix up 1 and l
2249: $newkey=~s/0/h/g; # and also 0 and O
2250: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2251: if ($existing{$newkey}) {
2252: $i--;
2253: } else {
1.364 www 2254: if (&put('accesskeys',
2255: { $newkey => '# generated '.localtime().
1.620 albertel 2256: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2257: '; '.$logentry },
2258: $cdom,$cnum) eq 'ok') {
1.344 www 2259: $total++;
2260: }
2261: }
2262: }
1.620 albertel 2263: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2264: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2265: return $total;
2266: }
2267:
2268: # ------------------------------------------------------- Validate an accesskey
2269:
2270: sub validate_access_key {
2271: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2272: $cdom=
1.620 albertel 2273: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2274: $cnum=
1.620 albertel 2275: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2276: $udom=$env{'user.domain'} unless (defined($udom));
2277: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2278: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2279: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2280: }
2281:
2282: # ------------------------------------- Find the section of student in a course
1.652 albertel 2283: sub devalidate_getsection_cache {
2284: my ($udom,$unam,$courseid)=@_;
2285: my $hashid="$udom:$unam:$courseid";
2286: &devalidate_cache_new('getsection',$hashid);
2287: }
1.298 matthew 2288:
1.815 albertel 2289: sub courseid_to_courseurl {
2290: my ($courseid) = @_;
2291: #already url style courseid
2292: return $courseid if ($courseid =~ m{^/});
2293:
2294: if (exists($env{'course.'.$courseid.'.num'})) {
2295: my $cnum = $env{'course.'.$courseid.'.num'};
2296: my $cdom = $env{'course.'.$courseid.'.domain'};
2297: return "/$cdom/$cnum";
2298: }
2299:
2300: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2301: if (exists($courseinfo{'num'})) {
2302: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2303: }
2304:
2305: return undef;
2306: }
2307:
1.298 matthew 2308: sub getsection {
2309: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2310: my $cachetime=1800;
1.551 albertel 2311:
2312: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2313: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2314: if (defined($cached)) { return $result; }
2315:
1.298 matthew 2316: my %Pending;
2317: my %Expired;
2318: #
2319: # Each role can either have not started yet (pending), be active,
2320: # or have expired.
2321: #
2322: # If there is an active role, we are done.
2323: #
2324: # If there is more than one role which has not started yet,
2325: # choose the one which will start sooner
2326: # If there is one role which has not started yet, return it.
2327: #
2328: # If there is more than one expired role, choose the one which ended last.
2329: # If there is a role which has expired, return it.
2330: #
1.815 albertel 2331: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2332: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2333: foreach my $key (keys(%roleshash)) {
1.479 albertel 2334: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2335: my $section=$1;
2336: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2337: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2338: my $now=time;
1.548 albertel 2339: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2340: $Expired{$end}=$section;
2341: next;
2342: }
1.548 albertel 2343: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2344: $Pending{$start}=$section;
2345: next;
2346: }
1.599 albertel 2347: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2348: }
2349: #
2350: # Presumedly there will be few matching roles from the above
2351: # loop and the sorting time will be negligible.
2352: if (scalar(keys(%Pending))) {
2353: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2354: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2355: }
2356: if (scalar(keys(%Expired))) {
2357: my @sorted = sort {$a <=> $b} keys(%Expired);
2358: my $time = pop(@sorted);
1.599 albertel 2359: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2360: }
1.599 albertel 2361: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2362: }
1.70 www 2363:
1.599 albertel 2364: sub save_cache {
2365: &purge_remembered();
1.722 albertel 2366: #&Apache::loncommon::validate_page();
1.620 albertel 2367: undef(%env);
1.780 albertel 2368: undef($env_loaded);
1.599 albertel 2369: }
1.452 albertel 2370:
1.599 albertel 2371: my $to_remember=-1;
2372: my %remembered;
2373: my %accessed;
2374: my $kicks=0;
2375: my $hits=0;
1.849 albertel 2376: sub make_key {
2377: my ($name,$id) = @_;
1.872 albertel 2378: if (length($id) > 65
2379: && length(&escape($id)) > 200) {
2380: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2381: }
1.849 albertel 2382: return &escape($name.':'.$id);
2383: }
2384:
1.599 albertel 2385: sub devalidate_cache_new {
2386: my ($name,$id,$debug) = @_;
2387: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2388: $id=&make_key($name,$id);
1.599 albertel 2389: $memcache->delete($id);
2390: delete($remembered{$id});
2391: delete($accessed{$id});
2392: }
2393:
2394: sub is_cached_new {
2395: my ($name,$id,$debug) = @_;
1.849 albertel 2396: $id=&make_key($name,$id);
1.599 albertel 2397: if (exists($remembered{$id})) {
1.1133 foxr 2398: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2399: $accessed{$id}=[&gettimeofday()];
2400: $hits++;
2401: return ($remembered{$id},1);
2402: }
2403: my $value = $memcache->get($id);
2404: if (!(defined($value))) {
2405: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2406: return (undef,undef);
1.416 albertel 2407: }
1.599 albertel 2408: if ($value eq '__undef__') {
2409: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2410: $value=undef;
2411: }
2412: &make_room($id,$value,$debug);
2413: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2414: return ($value,1);
2415: }
2416:
2417: sub do_cache_new {
2418: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2419: $id=&make_key($name,$id);
1.599 albertel 2420: my $setvalue=$value;
2421: if (!defined($setvalue)) {
2422: $setvalue='__undef__';
2423: }
1.623 albertel 2424: if (!defined($time) ) {
2425: $time=600;
2426: }
1.599 albertel 2427: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2428: my $result = $memcache->set($id,$setvalue,$time);
2429: if (! $result) {
1.872 albertel 2430: &logthis("caching of id -> $id failed");
1.910 albertel 2431: $memcache->disconnect_all();
1.872 albertel 2432: }
1.600 albertel 2433: # need to make a copy of $value
1.919 albertel 2434: &make_room($id,$value,$debug);
1.599 albertel 2435: return $value;
2436: }
2437:
2438: sub make_room {
2439: my ($id,$value,$debug)=@_;
1.919 albertel 2440:
2441: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2442: : $value;
1.599 albertel 2443: if ($to_remember<0) { return; }
2444: $accessed{$id}=[&gettimeofday()];
2445: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2446: my $to_kick;
2447: my $max_time=0;
2448: foreach my $other (keys(%accessed)) {
2449: if (&tv_interval($accessed{$other}) > $max_time) {
2450: $to_kick=$other;
2451: $max_time=&tv_interval($accessed{$other});
2452: }
2453: }
2454: delete($remembered{$to_kick});
2455: delete($accessed{$to_kick});
2456: $kicks++;
2457: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2458: return;
2459: }
2460:
1.599 albertel 2461: sub purge_remembered {
1.604 albertel 2462: #&logthis("Tossing ".scalar(keys(%remembered)));
2463: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2464: undef(%remembered);
2465: undef(%accessed);
1.428 albertel 2466: }
1.70 www 2467: # ------------------------------------- Read an entry from a user's environment
2468:
2469: sub userenvironment {
2470: my ($udom,$unam,@what)=@_;
1.976 raeburn 2471: my $items;
2472: foreach my $item (@what) {
2473: $items.=&escape($item).'&';
2474: }
2475: $items=~s/\&$//;
1.70 www 2476: my %returnhash=();
1.1009 raeburn 2477: my $uhome = &homeserver($unam,$udom);
2478: unless ($uhome eq 'no_host') {
2479: my @answer=split(/\&/,
2480: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2481: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2482: return %returnhash;
2483: }
1.1009 raeburn 2484: my $i;
2485: for ($i=0;$i<=$#what;$i++) {
2486: $returnhash{$what[$i]}=&unescape($answer[$i]);
2487: }
1.70 www 2488: }
2489: return %returnhash;
1.1 albertel 2490: }
2491:
1.617 albertel 2492: # ---------------------------------------------------------- Get a studentphoto
2493: sub studentphoto {
2494: my ($udom,$unam,$ext) = @_;
2495: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2496: if (defined($env{'request.course.id'})) {
1.708 raeburn 2497: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2498: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2499: return(&retrievestudentphoto($udom,$unam,$ext));
2500: } else {
2501: my ($result,$perm_reqd)=
1.707 albertel 2502: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2503: if ($result eq 'ok') {
2504: if (!($perm_reqd eq 'yes')) {
2505: return(&retrievestudentphoto($udom,$unam,$ext));
2506: }
2507: }
2508: }
2509: }
2510: } else {
2511: my ($result,$perm_reqd) =
1.707 albertel 2512: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2513: if ($result eq 'ok') {
2514: if (!($perm_reqd eq 'yes')) {
2515: return(&retrievestudentphoto($udom,$unam,$ext));
2516: }
2517: }
2518: }
2519: return '/adm/lonKaputt/lonlogo_broken.gif';
2520: }
2521:
2522: sub retrievestudentphoto {
2523: my ($udom,$unam,$ext,$type) = @_;
2524: my $home=&Apache::lonnet::homeserver($unam,$udom);
2525: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2526: if ($ret eq 'ok') {
2527: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2528: if ($type eq 'thumbnail') {
2529: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2530: }
2531: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2532: return $tokenurl;
2533: } else {
2534: if ($type eq 'thumbnail') {
2535: return '/adm/lonKaputt/genericstudent_tn.gif';
2536: } else {
2537: return '/adm/lonKaputt/lonlogo_broken.gif';
2538: }
1.617 albertel 2539: }
2540: }
2541:
1.263 www 2542: # -------------------------------------------------------------------- New chat
2543:
2544: sub chatsend {
1.724 raeburn 2545: my ($newentry,$anon,$group)=@_;
1.620 albertel 2546: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2547: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2548: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2549: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2550: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2551: &escape($newentry)).':'.$group,$chome);
1.292 www 2552: }
2553:
2554: # ------------------------------------------ Find current version of a resource
2555:
2556: sub getversion {
2557: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2558: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2559: return ¤tversion(&filelocation('',$fname));
2560: }
2561:
2562: sub currentversion {
2563: my $fname=shift;
2564: my $author=$fname;
2565: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2566: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2567: my $home=&homeserver($uname,$udom);
1.292 www 2568: if ($home eq 'no_host') {
2569: return -1;
2570: }
1.1112 www 2571: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2572: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2573: return -1;
2574: }
1.1112 www 2575: return $answer;
1.263 www 2576: }
2577:
1.1111 www 2578: #
2579: # Return special version number of resource if set by override, empty otherwise
2580: #
2581: sub usedversion {
2582: my $fname=shift;
2583: unless ($fname) { $fname=$env{'request.uri'}; }
2584: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2585: if ($urlversion) { return $urlversion; }
2586: return '';
2587: }
2588:
1.1 albertel 2589: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2590:
1.1 albertel 2591: sub subscribe {
2592: my $fname=shift;
1.761 raeburn 2593: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2594: $fname=~s/[\n\r]//g;
1.1 albertel 2595: my $author=$fname;
2596: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2597: my ($udom,$uname)=split(/\//,$author);
2598: my $home=homeserver($uname,$udom);
1.335 albertel 2599: if ($home eq 'no_host') {
2600: return 'not_found';
1.1 albertel 2601: }
2602: my $answer=reply("sub:$fname",$home);
1.64 www 2603: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2604: $answer.=' by '.$home;
2605: }
1.1 albertel 2606: return $answer;
2607: }
2608:
1.8 www 2609: # -------------------------------------------------------------- Replicate file
2610:
2611: sub repcopy {
2612: my $filename=shift;
1.23 www 2613: $filename=~s/\/+/\//g;
1.1142 raeburn 2614: my $londocroot = $perlvar{'lonDocRoot'};
2615: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2616: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2617: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2618: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2619: return &repcopy_userfile($filename);
2620: }
1.532 albertel 2621: $filename=~s/[\n\r]//g;
1.8 www 2622: my $transname="$filename.in.transfer";
1.828 www 2623: # FIXME: this should flock
1.607 raeburn 2624: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2625: my $remoteurl=subscribe($filename);
1.64 www 2626: if ($remoteurl =~ /^con_lost by/) {
2627: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2628: return 'unavailable';
1.8 www 2629: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2630: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2631: return 'not_found';
1.64 www 2632: } elsif ($remoteurl =~ /^rejected by/) {
2633: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2634: return 'forbidden';
1.20 www 2635: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2636: return 'ok';
1.8 www 2637: } else {
1.290 www 2638: my $author=$filename;
2639: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2640: my ($udom,$uname)=split(/\//,$author);
2641: my $home=homeserver($uname,$udom);
2642: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2643: my @parts=split(/\//,$filename);
2644: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2645: if ($path ne "$londocroot/res") {
1.8 www 2646: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2647: return 'bad_request';
1.8 www 2648: }
2649: my $count;
2650: for ($count=5;$count<$#parts;$count++) {
2651: $path.="/$parts[$count]";
2652: if ((-e $path)!=1) {
2653: mkdir($path,0777);
2654: }
2655: }
2656: my $ua=new LWP::UserAgent;
2657: my $request=new HTTP::Request('GET',"$remoteurl");
2658: my $response=$ua->request($request,$transname);
2659: if ($response->is_error()) {
2660: unlink($transname);
2661: my $message=$response->status_line;
1.672 albertel 2662: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2663: ." LWP get: $message: $filename</font>");
1.607 raeburn 2664: return 'unavailable';
1.8 www 2665: } else {
1.16 www 2666: if ($remoteurl!~/\.meta$/) {
2667: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2668: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2669: if ($mresponse->is_error()) {
2670: unlink($filename.'.meta');
2671: &logthis(
1.672 albertel 2672: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2673: }
2674: }
1.8 www 2675: rename($transname,$filename);
1.607 raeburn 2676: return 'ok';
1.8 www 2677: }
1.290 www 2678: }
1.8 www 2679: }
1.330 www 2680: }
2681:
2682: # ------------------------------------------------ Get server side include body
2683: sub ssi_body {
1.381 albertel 2684: my ($filelink,%form)=@_;
1.606 matthew 2685: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2686: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2687: }
1.953 www 2688: my $output='';
2689: my $response;
1.980 raeburn 2690: if ($filelink=~/^https?\:/) {
1.954 raeburn 2691: ($output,$response)=&externalssi($filelink);
1.953 www 2692: } else {
1.1004 droeschl 2693: $filelink .= $filelink=~/\?/ ? '&' : '?';
2694: $filelink .= 'inhibitmenu=yes';
1.953 www 2695: ($output,$response)=&ssi($filelink,%form);
2696: }
1.778 albertel 2697: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2698: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2699: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2700: if (wantarray) {
2701: return ($output, $response);
2702: } else {
2703: return $output;
2704: }
1.8 www 2705: }
2706:
1.15 www 2707: # --------------------------------------------------------- Server Side Include
2708:
1.782 albertel 2709: sub absolute_url {
2710: my ($host_name) = @_;
2711: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2712: if ($host_name eq '') {
2713: $host_name = $ENV{'SERVER_NAME'};
2714: }
2715: return $protocol.$host_name;
2716: }
2717:
1.942 foxr 2718: #
2719: # Server side include.
2720: # Parameters:
2721: # fn Possibly encrypted resource name/id.
2722: # form Hash that describes how the rendering should be done
2723: # and other things.
1.944 foxr 2724: # Returns:
1.950 raeburn 2725: # Scalar context: The content of the response.
2726: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2727: #
1.15 www 2728: sub ssi {
2729:
1.944 foxr 2730: my ($fn,%form)=@_;
1.15 www 2731: my $ua=new LWP::UserAgent;
1.23 www 2732: my $request;
1.711 albertel 2733:
2734: $form{'no_update_last_known'}=1;
1.895 albertel 2735: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2736: if (%form) {
1.782 albertel 2737: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2738: $request->content(join('&',map {
2739: my $name = escape($_);
2740: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2741: ? join("&$name=", map {escape($_) } @{$form{$_}})
2742: : &escape($form{$_}) );
2743: } keys(%form)));
1.23 www 2744: } else {
1.782 albertel 2745: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2746: }
2747:
1.15 www 2748: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2749: my $response= $ua->request($request);
1.944 foxr 2750: if (wantarray) {
1.1172.2.3 raeburn 2751: return ($response->content, $response);
1.944 foxr 2752: } else {
1.1172.2.3 raeburn 2753: return $response->content;
1.942 foxr 2754: }
1.324 www 2755: }
2756:
2757: sub externalssi {
2758: my ($url)=@_;
2759: my $ua=new LWP::UserAgent;
2760: my $request=new HTTP::Request('GET',$url);
2761: my $response=$ua->request($request);
1.954 raeburn 2762: if (wantarray) {
2763: return ($response->content, $response);
2764: } else {
2765: return $response->content;
2766: }
1.15 www 2767: }
1.254 www 2768:
1.492 albertel 2769: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2770:
2771: sub allowuploaded {
2772: my ($srcurl,$url)=@_;
2773: $url=&clutter(&declutter($url));
2774: my $dir=$url;
2775: $dir=~s/\/[^\/]+$//;
2776: my %httpref=();
2777: my $httpurl=&hreflocation('',$url);
2778: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2779: &Apache::lonnet::appenv(\%httpref);
1.254 www 2780: }
1.477 raeburn 2781:
1.1172.2.13 raeburn 2782: #
2783: # Determine if the current user should be able to edit a particular resource,
2784: # when viewing in course context.
2785: # (a) When viewing resource used to determine if "Edit" item is included in
2786: # Functions.
2787: # (b) When displaying folder contents in course editor, used to determine if
2788: # "Edit" link will be displayed alongside resource.
2789: #
2790: # input: six args -- filename (decluttered), course number, course domain,
2791: # url, symb (if registered) and group (if this is a group
2792: # item -- e.g., bulletin board, group page etc.).
2793: # output: array of five scalars --
2794: # $cfile -- url for file editing if editable on current server
2795: # $home -- homeserver of resource (i.e., for author if published,
2796: # or course if uploaded.).
2797: # $switchserver -- 1 if server switch will be needed.
2798: # $forceedit -- 1 if icon/link should be to go to edit mode
2799: # $forceview -- 1 if icon/link should be to go to view mode
2800: #
2801:
2802: sub can_edit_resource {
2803: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2804: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2805: #
2806: # For aboutme pages user can only edit his/her own.
2807: #
2808: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2809: my ($sdom,$sname) = ($1,$2);
2810: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2811: $home = $env{'user.home'};
2812: $cfile = $resurl;
2813: if ($env{'form.forceedit'}) {
2814: $forceview = 1;
2815: } else {
2816: $forceedit = 1;
2817: }
2818: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2819: } else {
2820: return;
2821: }
2822: }
2823:
2824: if ($env{'request.course.id'}) {
2825: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2826: if ($group ne '') {
2827: # if this is a group homepage or group bulletin board, check group privs
2828: my $allowed = 0;
2829: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2830: if ((&allowed('mdg',$env{'request.course.id'}.
2831: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2832: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2833: $allowed = 1;
2834: }
2835: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2836: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2837: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2838: $allowed = 1;
2839: }
2840: }
2841: if ($allowed) {
2842: $home=&homeserver($cnum,$cdom);
2843: if ($env{'form.forceedit'}) {
2844: $forceview = 1;
2845: } else {
2846: $forceedit = 1;
2847: }
2848: $cfile = $resurl;
2849: } else {
2850: return;
2851: }
2852: } else {
1.1172.2.15 raeburn 2853: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2854: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2855: return;
2856: }
2857: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2858: #
2859: # No edit allowed where CC has switched to student role.
2860: #
2861: return;
2862: }
2863: }
2864: }
2865:
2866: if ($file ne '') {
2867: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2868: if (&is_course_upload($file,$cnum,$cdom)) {
2869: $uploaded = 1;
2870: $incourse = 1;
2871: if ($file =~/\.(htm|html|css|js|txt)$/) {
2872: $cfile = &hreflocation('',$file);
2873: if ($env{'form.forceedit'}) {
2874: $forceview = 1;
2875: } else {
2876: $forceedit = 1;
2877: }
2878: }
2879: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2880: $incourse = 1;
2881: if ($env{'form.forceedit'}) {
2882: $forceview = 1;
2883: } else {
2884: $forceedit = 1;
2885: }
2886: $cfile = $resurl;
2887: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2888: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2889: $incourse = 1;
2890: if ($env{'form.forceedit'}) {
2891: $forceview = 1;
2892: } else {
2893: $forceedit = 1;
2894: }
2895: $cfile = $resurl;
2896: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2897: $incourse = 1;
2898: $cfile = $resurl.'/smpedit';
2899: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2900: $incourse = 1;
2901: if ($env{'form.forceedit'}) {
2902: $forceview = 1;
2903: } else {
2904: $forceedit = 1;
2905: }
2906: $cfile = $resurl;
1.1172.2.15 raeburn 2907: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2908: $incourse = 1;
2909: if ($env{'form.forceedit'}) {
2910: $forceview = 1;
2911: } else {
2912: $forceedit = 1;
2913: }
2914: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2915: }
2916: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2917: my $template = '/res/lib/templates/simpleproblem.problem';
2918: if (&is_on_map($template)) {
2919: $incourse = 1;
2920: $forceview = 1;
2921: $cfile = $template;
2922: }
2923: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2924: $incourse = 1;
2925: if ($env{'form.forceedit'}) {
2926: $forceview = 1;
2927: } else {
2928: $forceedit = 1;
2929: }
2930: $cfile = $resurl;
2931: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2932: $incourse = 1;
2933: $forceview = 1;
2934: if ($symb) {
2935: my ($map,$id,$res)=&decode_symb($symb);
2936: $env{'request.symb'} = $symb;
2937: $cfile = &clutter($res);
2938: } else {
2939: $cfile = $env{'form.suppurl'};
2940: $cfile =~ s{^http://}{};
2941: $cfile = '/adm/wrapper/ext/'.$cfile;
2942: }
1.1172.2.31 raeburn 2943: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2944: if ($env{'form.forceedit'}) {
2945: $forceview = 1;
2946: } else {
2947: $forceedit = 1;
2948: }
2949: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2950: }
2951: }
2952: if ($uploaded || $incourse) {
2953: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2954: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2955: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2956: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2957: # Check that the user has permission to edit this resource
2958: my $setpriv = 1;
2959: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2960: if (defined($cfudom)) {
2961: $home=&homeserver($cfuname,$cfudom);
2962: $cfile=$file;
2963: }
2964: }
2965: if (($cfile ne '') && (!$incourse || $uploaded) &&
2966: (($home ne '') && ($home ne 'no_host'))) {
2967: my @ids=¤t_machine_ids();
2968: unless (grep(/^\Q$home\E$/,@ids)) {
2969: $switchserver=1;
2970: }
2971: }
2972: }
2973: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2974: }
2975:
2976: sub is_course_upload {
2977: my ($file,$cnum,$cdom) = @_;
2978: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2979: $uploadpath =~ s{^\/}{};
2980: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2981: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2982: return 1;
2983: }
2984: return;
2985: }
2986:
2987: sub in_course {
2988: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2989: if ($hideprivileged) {
2990: my $skipuser;
1.1172.2.23 raeburn 2991: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2992: my @possdoms = ($cdom);
2993: if ($coursehash{'checkforpriv'}) {
2994: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2995: }
2996: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2997: $skipuser = 1;
2998: if ($coursehash{'nothideprivileged'}) {
2999: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3000: my $user;
3001: if ($item =~ /:/) {
3002: $user = $item;
3003: } else {
3004: $user = join(':',split(/[\@]/,$item));
3005: }
3006: if ($user eq $uname.':'.$udom) {
3007: undef($skipuser);
3008: last;
3009: }
3010: }
3011: }
3012: if ($skipuser) {
3013: return 0;
3014: }
3015: }
3016: }
3017: $type ||= 'any';
3018: if (!defined($cdom) || !defined($cnum)) {
3019: my $cid = $env{'request.course.id'};
3020: $cdom = $env{'course.'.$cid.'.domain'};
3021: $cnum = $env{'course.'.$cid.'.num'};
3022: }
3023: my $typesref;
3024: if (($type eq 'any') || ($type eq 'all')) {
3025: $typesref = ['active','previous','future'];
3026: } elsif ($type eq 'previous' || $type eq 'future') {
3027: $typesref = [$type];
3028: }
3029: my %roles = &get_my_roles($uname,$udom,'userroles',
3030: $typesref,undef,[$cdom]);
3031: my ($tmp) = keys(%roles);
3032: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3033: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3034: if (@course_roles > 0) {
3035: return 1;
3036: }
3037: return 0;
3038: }
3039:
1.478 albertel 3040: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3041: # input: action, courseID, current domain, intended
1.637 raeburn 3042: # path to file, source of file, instruction to parse file for objects,
3043: # ref to hash for embedded objects,
3044: # ref to hash for codebase of java objects.
1.1095 raeburn 3045: # reference to scalar to accommodate mime type determined
3046: # from File::MMagic if $parser = parse.
1.637 raeburn 3047: #
1.485 raeburn 3048: # output: url to file (if action was uploaddoc),
3049: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3050: #
1.478 albertel 3051: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3052: # course.
1.477 raeburn 3053: #
1.478 albertel 3054: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3055: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3056: # course's home server.
1.477 raeburn 3057: #
1.478 albertel 3058: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3059: # be copied from $source (current location) to
3060: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3061: # and will then be copied to
3062: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3063: # course's home server.
1.485 raeburn 3064: #
1.481 raeburn 3065: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3066: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3067: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3068: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3069: # in course's home server.
1.637 raeburn 3070: #
1.477 raeburn 3071:
3072: sub process_coursefile {
1.1095 raeburn 3073: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3074: $mimetype)=@_;
1.477 raeburn 3075: my $fetchresult;
1.638 albertel 3076: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3077: if ($action eq 'propagate') {
1.638 albertel 3078: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3079: $home);
1.481 raeburn 3080: } else {
1.477 raeburn 3081: my $fpath = '';
3082: my $fname = $file;
1.478 albertel 3083: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3084: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3085: my $filepath = &build_filepath($fpath);
1.481 raeburn 3086: if ($action eq 'copy') {
3087: if ($source eq '') {
3088: $fetchresult = 'no source file';
3089: return $fetchresult;
3090: } else {
3091: my $destination = $filepath.'/'.$fname;
3092: rename($source,$destination);
3093: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3094: $home);
1.481 raeburn 3095: }
3096: } elsif ($action eq 'uploaddoc') {
3097: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3098: print $fh $env{'form.'.$source};
1.481 raeburn 3099: close($fh);
1.637 raeburn 3100: if ($parser eq 'parse') {
1.1024 raeburn 3101: my $mm = new File::MMagic;
1.1095 raeburn 3102: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3103: if ($type eq 'text/html') {
1.1024 raeburn 3104: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3105: unless ($parse_result eq 'ok') {
3106: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3107: }
1.637 raeburn 3108: }
1.1095 raeburn 3109: if (ref($mimetype)) {
3110: $$mimetype = $type;
3111: }
1.637 raeburn 3112: }
1.477 raeburn 3113: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3114: $home);
1.481 raeburn 3115: if ($fetchresult eq 'ok') {
3116: return '/uploaded/'.$fpath.'/'.$fname;
3117: } else {
3118: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3119: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3120: return '/adm/notfound.html';
3121: }
1.477 raeburn 3122: }
3123: }
1.485 raeburn 3124: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3125: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3126: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3127: }
3128: return $fetchresult;
3129: }
3130:
1.637 raeburn 3131: sub build_filepath {
3132: my ($fpath) = @_;
3133: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3134: unless ($fpath eq '') {
3135: my @parts=split('/',$fpath);
3136: foreach my $part (@parts) {
3137: $filepath.= '/'.$part;
3138: if ((-e $filepath)!=1) {
3139: mkdir($filepath,0777);
3140: }
3141: }
3142: }
3143: return $filepath;
3144: }
3145:
3146: sub store_edited_file {
1.638 albertel 3147: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3148: my $file = $primary_url;
3149: $file =~ s#^/uploaded/$docudom/$docuname/##;
3150: my $fpath = '';
3151: my $fname = $file;
3152: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3153: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3154: my $filepath = &build_filepath($fpath);
3155: open(my $fh,'>'.$filepath.'/'.$fname);
3156: print $fh $content;
3157: close($fh);
1.638 albertel 3158: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3159: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3160: $home);
1.637 raeburn 3161: if ($$fetchresult eq 'ok') {
3162: return '/uploaded/'.$fpath.'/'.$fname;
3163: } else {
1.638 albertel 3164: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3165: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3166: return '/adm/notfound.html';
3167: }
3168: }
3169:
1.531 albertel 3170: sub clean_filename {
1.831 albertel 3171: my ($fname,$args)=@_;
1.315 www 3172: # Replace Windows backslashes by forward slashes
1.257 www 3173: $fname=~s/\\/\//g;
1.831 albertel 3174: if (!$args->{'keep_path'}) {
3175: # Get rid of everything but the actual filename
3176: $fname=~s/^.*\/([^\/]+)$/$1/;
3177: }
1.315 www 3178: # Replace spaces by underscores
3179: $fname=~s/\s+/\_/g;
3180: # Replace all other weird characters by nothing
1.831 albertel 3181: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3182: # Replace all .\d. sequences with _\d. so they no longer look like version
3183: # numbers
3184: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3185: return $fname;
3186: }
1.1051 raeburn 3187: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3188: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3189: # image with the same aspect ratio as the original, but with dimensions which do
3190: # not exceed $resizewidth and $resizeheight.
3191:
1.984 neumanie 3192: sub resizeImage {
1.1051 raeburn 3193: my ($img_path,$resizewidth,$resizeheight) = @_;
3194: my $ima = Image::Magick->new;
3195: my $resized;
3196: if (-e $img_path) {
3197: $ima->Read($img_path);
3198: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3199: my $width = $ima->Get('width');
3200: my $height = $ima->Get('height');
3201: if ($width > $resizewidth) {
3202: my $factor = $width/$resizewidth;
3203: my $newheight = $height/$factor;
3204: $ima->Scale(width=>$resizewidth,height=>$newheight);
3205: $resized = 1;
3206: }
3207: }
3208: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3209: my $width = $ima->Get('width');
3210: my $height = $ima->Get('height');
3211: if ($height > $resizeheight) {
3212: my $factor = $height/$resizeheight;
3213: my $newwidth = $width/$factor;
3214: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3215: $resized = 1;
3216: }
3217: }
3218: if ($resized) {
3219: $ima->Write($img_path);
3220: }
3221: }
3222: return;
1.977 amueller 3223: }
3224:
1.608 albertel 3225: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3226: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3227: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3228: # $context - possible values: coursedoc, existingfile, overwrite,
3229: # canceloverwrite, or ''.
3230: # if 'coursedoc': upload to the current course
3231: # if 'existingfile': write file to tmp/overwrites directory
3232: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3233: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3234: # $subdir - directory in userfile to store the file into
1.858 raeburn 3235: # $parser - instruction to parse file for objects ($parser = parse)
3236: # $allfiles - reference to hash for embedded objects
3237: # $codebase - reference to hash for codebase of java objects
3238: # $desuname - username for permanent storage of uploaded file
3239: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3240: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3241: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3242: # $resizewidth - width (pixels) to which to resize uploaded image
3243: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3244: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3245: # from File::MMagic.
1.858 raeburn 3246: #
1.686 albertel 3247: # output: url of file in userspace, or error: <message>
3248: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3249:
1.531 albertel 3250: sub userfileupload {
1.1090 raeburn 3251: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3252: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3253: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3254: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3255: $fname=&clean_filename($fname);
1.1090 raeburn 3256: # See if there is anything left
1.257 www 3257: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3258: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3259: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3260: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3261: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3262: my $now = time;
1.1090 raeburn 3263: my $filepath;
1.1095 raeburn 3264: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3265: $filepath = 'tmp/helprequests/'.$now;
3266: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3267: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3268: '_'.$env{'user.domain'}.'/pending';
3269: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3270: my ($docuname,$docudom);
3271: if ($destudom) {
3272: $docudom = $destudom;
3273: } else {
3274: $docudom = $env{'user.domain'};
3275: }
3276: if ($destuname) {
3277: $docuname = $destuname;
3278: } else {
3279: $docuname = $env{'user.name'};
3280: }
3281: if (exists($env{'form.group'})) {
3282: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3283: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3284: }
3285: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3286: if ($context eq 'canceloverwrite') {
3287: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3288: if (-e $tempfile) {
3289: my @info = stat($tempfile);
3290: if ($info[9] eq $env{'form.timestamp'}) {
3291: unlink($tempfile);
3292: }
3293: }
3294: return;
1.523 raeburn 3295: }
3296: }
1.1090 raeburn 3297: # Create the directory if not present
1.741 raeburn 3298: my @parts=split(/\//,$filepath);
3299: my $fullpath = $perlvar{'lonDaemons'};
3300: for (my $i=0;$i<@parts;$i++) {
3301: $fullpath .= '/'.$parts[$i];
3302: if ((-e $fullpath)!=1) {
3303: mkdir($fullpath,0777);
3304: }
3305: }
3306: open(my $fh,'>'.$fullpath.'/'.$fname);
3307: print $fh $env{'form.'.$formname};
3308: close($fh);
1.1090 raeburn 3309: if ($context eq 'existingfile') {
3310: my @info = stat($fullpath.'/'.$fname);
3311: return ($fullpath.'/'.$fname,$info[9]);
3312: } else {
3313: return $fullpath.'/'.$fname;
3314: }
1.523 raeburn 3315: }
1.995 raeburn 3316: if ($subdir eq 'scantron') {
3317: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3318: } else {
1.995 raeburn 3319: $fname="$subdir/$fname";
3320: }
1.1090 raeburn 3321: if ($context eq 'coursedoc') {
1.638 albertel 3322: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3323: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3324: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3325: return &finishuserfileupload($docuname,$docudom,
3326: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3327: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3328: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3329: } else {
1.1172.2.21 raeburn 3330: if ($env{'form.folder'}) {
3331: $fname=$env{'form.folder'}.'/'.$fname;
3332: }
1.638 albertel 3333: return &process_coursefile('uploaddoc',$docuname,$docudom,
3334: $fname,$formname,$parser,
1.1095 raeburn 3335: $allfiles,$codebase,$mimetype);
1.481 raeburn 3336: }
1.719 banghart 3337: } elsif (defined($destuname)) {
3338: my $docuname=$destuname;
3339: my $docudom=$destudom;
1.860 raeburn 3340: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3341: $parser,$allfiles,$codebase,
1.1051 raeburn 3342: $thumbwidth,$thumbheight,
1.1095 raeburn 3343: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3344: } else {
1.638 albertel 3345: my $docuname=$env{'user.name'};
3346: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3347: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3348: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3349: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3350: }
1.860 raeburn 3351: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3352: $parser,$allfiles,$codebase,
1.1051 raeburn 3353: $thumbwidth,$thumbheight,
1.1095 raeburn 3354: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3355: }
1.271 www 3356: }
3357:
3358: sub finishuserfileupload {
1.860 raeburn 3359: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3360: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3361: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3362: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3363:
1.860 raeburn 3364: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3365: $file=$fname;
3366: if ($fname=~m|/|) {
3367: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3368: $path.=$fnamepath.'/';
3369: }
1.259 www 3370: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3371: my $count;
3372: for ($count=4;$count<=$#parts;$count++) {
3373: $filepath.="/$parts[$count]";
3374: if ((-e $filepath)!=1) {
3375: mkdir($filepath,0777);
3376: }
3377: }
1.984 neumanie 3378:
1.258 www 3379: # Save the file
3380: {
1.701 albertel 3381: if (!open(FH,'>'.$filepath.'/'.$file)) {
3382: &logthis('Failed to create '.$filepath.'/'.$file);
3383: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3384: return '/adm/notfound.html';
3385: }
1.1090 raeburn 3386: if ($context eq 'overwrite') {
1.1117 foxr 3387: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3388: my $target = $filepath.'/'.$file;
3389: if (-e $source) {
3390: my @info = stat($source);
3391: if ($info[9] eq $env{'form.timestamp'}) {
3392: unless (&File::Copy::move($source,$target)) {
3393: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3394: return "Moving from $source failed";
3395: }
3396: } else {
3397: return "Temporary file: $source had unexpected date/time for last modification";
3398: }
3399: } else {
3400: return "Temporary file: $source missing";
3401: }
3402: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3403: &logthis('Failed to write to '.$filepath.'/'.$file);
3404: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3405: return '/adm/notfound.html';
3406: }
1.570 albertel 3407: close(FH);
1.1051 raeburn 3408: if ($resizewidth && $resizeheight) {
3409: my $mm = new File::MMagic;
3410: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3411: if ($mime_type =~ m{^image/}) {
3412: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3413: }
1.977 amueller 3414: }
1.258 www 3415: }
1.1152 raeburn 3416: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3417: if (ref($mimetype)) {
3418: if ($$mimetype eq '') {
3419: my $mm = new File::MMagic;
3420: my $type = $mm->checktype_filename($filepath.'/'.$file);
3421: $$mimetype = $type;
3422: }
3423: }
3424: }
1.637 raeburn 3425: if ($parser eq 'parse') {
1.1152 raeburn 3426: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3427: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3428: $allfiles,$codebase);
3429: unless ($parse_result eq 'ok') {
3430: &logthis('Failed to parse '.$filepath.$file.
3431: ' for embedded media: '.$parse_result);
3432: }
1.637 raeburn 3433: }
3434: }
1.860 raeburn 3435: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3436: my $input = $filepath.'/'.$file;
3437: my $output = $filepath.'/'.'tn-'.$file;
3438: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3439: system("convert -sample $thumbsize $input $output");
3440: if (-e $filepath.'/'.'tn-'.$file) {
3441: $fetchthumb = 1;
3442: }
3443: }
1.858 raeburn 3444:
1.259 www 3445: # Notify homeserver to grep it
3446: #
1.984 neumanie 3447: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3448: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3449: if ($fetchresult eq 'ok') {
1.860 raeburn 3450: if ($fetchthumb) {
3451: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3452: if ($thumbresult ne 'ok') {
3453: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3454: $docuhome.': '.$thumbresult);
3455: }
3456: }
1.259 www 3457: #
1.258 www 3458: # Return the URL to it
1.494 albertel 3459: return '/uploaded/'.$path.$file;
1.263 www 3460: } else {
1.494 albertel 3461: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3462: ': '.$fetchresult);
1.263 www 3463: return '/adm/notfound.html';
1.858 raeburn 3464: }
1.493 albertel 3465: }
3466:
1.637 raeburn 3467: sub extract_embedded_items {
1.961 raeburn 3468: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3469: my @state = ();
1.1164 raeburn 3470: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3471: my %javafiles = (
3472: codebase => '',
3473: code => '',
3474: archive => ''
3475: );
3476: my %mediafiles = (
3477: src => '',
3478: movie => '',
3479: );
1.648 raeburn 3480: my $p;
3481: if ($content) {
3482: $p = HTML::LCParser->new($content);
3483: } else {
1.961 raeburn 3484: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3485: }
1.641 albertel 3486: while (my $t=$p->get_token()) {
1.640 albertel 3487: if ($t->[0] eq 'S') {
3488: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3489: push(@state, $tagname);
1.648 raeburn 3490: if (lc($tagname) eq 'allow') {
3491: &add_filetype($allfiles,$attr->{'src'},'src');
3492: }
1.640 albertel 3493: if (lc($tagname) eq 'img') {
3494: &add_filetype($allfiles,$attr->{'src'},'src');
3495: }
1.886 albertel 3496: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3497: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3498: &add_filetype($allfiles,$attr->{'href'},'href');
3499: }
1.886 albertel 3500: }
1.645 raeburn 3501: if (lc($tagname) eq 'script') {
1.1164 raeburn 3502: my $src;
1.645 raeburn 3503: if ($attr->{'archive'} =~ /\.jar$/i) {
3504: &add_filetype($allfiles,$attr->{'archive'},'archive');
3505: } else {
1.1164 raeburn 3506: if ($attr->{'src'} ne '') {
3507: $src = $attr->{'src'};
3508: &add_filetype($allfiles,$src,'src');
3509: }
3510: }
3511: my $text = $p->get_trimmed_text();
3512: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3513: my @swfargs = split(/,/,$1);
3514: foreach my $item (@swfargs) {
3515: $item =~ s/["']//g;
3516: $item =~ s/^\s+//;
3517: $item =~ s/\s+$//;
3518: }
3519: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3520: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3521: push(@{$related{$swfargs[0]}},$swfargs[2]);
3522: } else {
3523: $related{$swfargs[0]} = [$swfargs[2]];
3524: }
3525: }
1.645 raeburn 3526: }
3527: }
3528: if (lc($tagname) eq 'link') {
3529: if (lc($attr->{'rel'}) eq 'stylesheet') {
3530: &add_filetype($allfiles,$attr->{'href'},'href');
3531: }
3532: }
1.640 albertel 3533: if (lc($tagname) eq 'object' ||
3534: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3535: foreach my $item (keys(%javafiles)) {
3536: $javafiles{$item} = '';
3537: }
1.1164 raeburn 3538: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3539: $lastids{lc($tagname)} = $attr->{'id'};
3540: }
1.640 albertel 3541: }
3542: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3543: my $name = lc($attr->{'name'});
3544: foreach my $item (keys(%javafiles)) {
3545: if ($name eq $item) {
3546: $javafiles{$item} = $attr->{'value'};
3547: last;
3548: }
3549: }
1.1164 raeburn 3550: my $pathfrom;
1.640 albertel 3551: foreach my $item (keys(%mediafiles)) {
3552: if ($name eq $item) {
1.1164 raeburn 3553: $pathfrom = $attr->{'value'};
3554: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3555: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3556: last;
3557: }
3558: }
1.1164 raeburn 3559: if ($name eq 'flashvars') {
3560: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3561: }
3562: if ($pathfrom ne '') {
3563: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3564: $pathfrom);
3565: }
1.640 albertel 3566: }
3567: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3568: foreach my $item (keys(%javafiles)) {
3569: if ($attr->{$item}) {
3570: $javafiles{$item} = $attr->{$item};
3571: last;
3572: }
3573: }
3574: foreach my $item (keys(%mediafiles)) {
3575: if ($attr->{$item}) {
3576: &add_filetype($allfiles,$attr->{$item},$item);
3577: last;
3578: }
3579: }
1.1164 raeburn 3580: if (lc($tagname) eq 'embed') {
3581: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3582: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3583: $attr->{'src'});
3584: }
3585: }
1.640 albertel 3586: }
1.1172.2.35 raeburn 3587: if (lc($tagname) eq 'iframe') {
3588: my $src = $attr->{'src'} ;
3589: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3590: &add_filetype($allfiles,$src,'src');
3591: } elsif ($src =~ m{^/}) {
3592: if ($env{'request.course.id'}) {
3593: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3594: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3595: my $url = &hreflocation('',$fullpath);
3596: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3597: my $relpath = $1;
3598: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3599: &add_filetype($allfiles,$1,'src');
3600: }
3601: }
3602: }
3603: }
3604: }
1.1164 raeburn 3605: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3606: pop(@state);
1.1164 raeburn 3607: }
1.640 albertel 3608: } elsif ($t->[0] eq 'E') {
3609: my ($tagname) = ($t->[1]);
3610: if ($javafiles{'codebase'} ne '') {
3611: $javafiles{'codebase'} .= '/';
3612: }
3613: if (lc($tagname) eq 'applet' ||
3614: lc($tagname) eq 'object' ||
3615: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3616: ) {
3617: foreach my $item (keys(%javafiles)) {
3618: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3619: my $file=$javafiles{'codebase'}.$javafiles{$item};
3620: &add_filetype($allfiles,$file,$item);
3621: }
3622: }
3623: }
3624: pop @state;
3625: }
3626: }
1.1164 raeburn 3627: foreach my $id (sort(keys(%flashvars))) {
3628: if ($shockwave{$id} ne '') {
3629: my @pairs = split(/\&/,$flashvars{$id});
3630: foreach my $pair (@pairs) {
3631: my ($key,$value) = split(/\=/,$pair);
3632: if ($key eq 'thumb') {
3633: &add_filetype($allfiles,$value,$key);
3634: } elsif ($key eq 'content') {
3635: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3636: my ($ext) = ($value =~ /\.([^.]+)$/);
3637: if ($ext ne '') {
3638: &add_filetype($allfiles,$path.$value,$ext);
3639: }
3640: }
3641: }
3642: }
3643: }
1.637 raeburn 3644: return 'ok';
3645: }
3646:
1.639 albertel 3647: sub add_filetype {
3648: my ($allfiles,$file,$type)=@_;
3649: if (exists($allfiles->{$file})) {
3650: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3651: push(@{$allfiles->{$file}}, &escape($type));
3652: }
3653: } else {
3654: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3655: }
3656: }
3657:
1.1164 raeburn 3658: sub embedded_dependency {
3659: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3660: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3661: if (($identifier ne '') &&
3662: (ref($related->{$identifier}) eq 'ARRAY') &&
3663: ($pathfrom ne '')) {
3664: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3665: foreach my $dep (@{$related->{$identifier}}) {
3666: &add_filetype($allfiles,$path.$dep,'object');
3667: }
3668: }
3669: }
3670: return;
3671: }
3672:
1.493 albertel 3673: sub removeuploadedurl {
1.984 neumanie 3674: my ($url)=@_;
3675: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3676: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3677: }
3678:
3679: sub removeuserfile {
3680: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3681: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3682: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3683: if ($result eq 'ok') {
1.798 raeburn 3684: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3685: my $metafile = $fname.'.meta';
3686: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3687: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3688: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3689: my $sqlresult =
1.823 albertel 3690: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3691: 'portfolio_metadata',$group,
3692: 'delete');
1.798 raeburn 3693: }
3694: }
3695: return $result;
1.257 www 3696: }
1.15 www 3697:
1.530 albertel 3698: sub mkdiruserfile {
3699: my ($docuname,$docudom,$dir)=@_;
3700: my $home=&homeserver($docuname,$docudom);
3701: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3702: }
3703:
1.531 albertel 3704: sub renameuserfile {
3705: my ($docuname,$docudom,$old,$new)=@_;
3706: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3707: my $result = &reply("renameuserfile:$docudom:$docuname:".
3708: &escape("$old").':'.&escape("$new"),$home);
3709: if ($result eq 'ok') {
3710: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3711: my $oldmeta = $old.'.meta';
3712: my $newmeta = $new.'.meta';
3713: my $metaresult =
3714: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3715: my $url = "/uploaded/$docudom/$docuname/$old";
3716: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3717: my $sqlresult =
1.823 albertel 3718: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3719: 'portfolio_metadata',$group,
3720: 'delete');
1.798 raeburn 3721: }
3722: }
3723: return $result;
1.531 albertel 3724: }
3725:
1.14 www 3726: # ------------------------------------------------------------------------- Log
3727:
3728: sub log {
3729: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3730: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3731: }
3732:
3733: # ------------------------------------------------------------------ Course Log
1.352 www 3734: #
3735: # This routine flushes several buffers of non-mission-critical nature
3736: #
1.157 www 3737:
3738: sub flushcourselogs {
1.352 www 3739: &logthis('Flushing log buffers');
3740: #
3741: # course logs
3742: # This is a log of all transactions in a course, which can be used
3743: # for data mining purposes
3744: #
3745: # It also collects the courseid database, which lists last transaction
3746: # times and course titles for all courseids
3747: #
3748: my %courseidbuffer=();
1.921 raeburn 3749: foreach my $crsid (keys(%courselogs)) {
1.352 www 3750: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3751: &escape($courselogs{$crsid}),
3752: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3753: delete $courselogs{$crsid};
3754: } else {
3755: &logthis('Failed to flush log buffer for '.$crsid);
3756: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3757: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3758: " exceeded maximum size, deleting.</font>");
3759: delete $courselogs{$crsid};
3760: }
1.352 www 3761: }
1.920 raeburn 3762: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3763: 'description' => $coursedescrbuf{$crsid},
3764: 'inst_code' => $courseinstcodebuf{$crsid},
3765: 'type' => $coursetypebuf{$crsid},
3766: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3767: };
1.191 harris41 3768: }
1.352 www 3769: #
3770: # Write course id database (reverse lookup) to homeserver of courses
3771: # Is used in pickcourse
3772: #
1.840 albertel 3773: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3774: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3775: $courseidbuffer{$crs_home},
3776: $crs_home,'timeonly');
1.352 www 3777: }
3778: #
3779: # File accesses
3780: # Writes to the dynamic metadata of resources to get hit counts, etc.
3781: #
1.449 matthew 3782: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3783: if ($entry =~ /___count$/) {
3784: my ($dom,$name);
1.807 albertel 3785: ($dom,$name,undef)=
1.811 albertel 3786: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3787: if (! defined($dom) || $dom eq '' ||
3788: ! defined($name) || $name eq '') {
1.620 albertel 3789: my $cid = $env{'request.course.id'};
3790: $dom = $env{'request.'.$cid.'.domain'};
3791: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3792: }
1.450 matthew 3793: my $value = $accesshash{$entry};
3794: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3795: my %temphash=($url => $value);
1.449 matthew 3796: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3797: if ($result eq 'ok') {
3798: delete $accesshash{$entry};
3799: }
3800: } else {
1.811 albertel 3801: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3802: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3803: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3804: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3805: delete $accesshash{$entry};
3806: }
1.185 www 3807: }
1.191 harris41 3808: }
1.352 www 3809: #
3810: # Roles
3811: # Reverse lookup of user roles for course faculty/staff and co-authorship
3812: #
1.800 albertel 3813: foreach my $entry (keys(%userrolehash)) {
1.351 www 3814: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3815: split(/\:/,$entry);
3816: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3817: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3818: $rudom,$runame) eq 'ok') {
3819: delete $userrolehash{$entry};
3820: }
3821: }
1.662 raeburn 3822: #
3823: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3824: #
3825: my %domrolebuffer = ();
1.1000 raeburn 3826: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3827: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3828: if ($domrolebuffer{$rudom}) {
3829: $domrolebuffer{$rudom}.='&'.&escape($entry).
3830: '='.&escape($domainrolehash{$entry});
3831: } else {
3832: $domrolebuffer{$rudom}.=&escape($entry).
3833: '='.&escape($domainrolehash{$entry});
3834: }
3835: delete $domainrolehash{$entry};
3836: }
3837: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3838: my %servers = &get_servers($dom,'library');
3839: foreach my $tryserver (keys(%servers)) {
3840: unless (&reply('domroleput:'.$dom.':'.
3841: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3842: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3843: }
1.662 raeburn 3844: }
3845: }
1.186 www 3846: $dumpcount++;
1.157 www 3847: }
3848:
3849: sub courselog {
3850: my $what=shift;
1.158 www 3851: $what=time.':'.$what;
1.620 albertel 3852: unless ($env{'request.course.id'}) { return ''; }
3853: $coursedombuf{$env{'request.course.id'}}=
3854: $env{'course.'.$env{'request.course.id'}.'.domain'};
3855: $coursenumbuf{$env{'request.course.id'}}=
3856: $env{'course.'.$env{'request.course.id'}.'.num'};
3857: $coursehombuf{$env{'request.course.id'}}=
3858: $env{'course.'.$env{'request.course.id'}.'.home'};
3859: $coursedescrbuf{$env{'request.course.id'}}=
3860: $env{'course.'.$env{'request.course.id'}.'.description'};
3861: $courseinstcodebuf{$env{'request.course.id'}}=
3862: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3863: $courseownerbuf{$env{'request.course.id'}}=
3864: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3865: $coursetypebuf{$env{'request.course.id'}}=
3866: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3867: if (defined $courselogs{$env{'request.course.id'}}) {
3868: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3869: } else {
1.620 albertel 3870: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3871: }
1.620 albertel 3872: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3873: &flushcourselogs();
3874: }
1.158 www 3875: }
3876:
3877: sub courseacclog {
3878: my $fnsymb=shift;
1.620 albertel 3879: unless ($env{'request.course.id'}) { return ''; }
3880: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3881: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3882: $what.=':POST';
1.583 matthew 3883: # FIXME: Probably ought to escape things....
1.800 albertel 3884: foreach my $key (keys(%env)) {
3885: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3886: my $formitem = $1;
3887: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3888: $what.=':'.$formitem.'='.$env{$key};
3889: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3890: $what.=':'.$formitem.'='.$env{$key};
3891: }
1.158 www 3892: }
1.191 harris41 3893: }
1.583 matthew 3894: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3895: # FIXME: We should not be depending on a form parameter that someone
3896: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3897: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3898: $what.= ':POST';
3899: # FIXME: Probably ought to escape things....
3900: foreach my $element ('courseexp','crsfulltext','crsrelated',
3901: 'crsdiscuss') {
1.620 albertel 3902: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3903: }
3904: }
1.158 www 3905: }
3906: &courselog($what);
1.149 www 3907: }
3908:
1.185 www 3909: sub countacc {
3910: my $url=&declutter(shift);
1.458 matthew 3911: return if (! defined($url) || $url eq '');
1.620 albertel 3912: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3913: #
3914: # Mark that this url was used in this course
3915: #
1.620 albertel 3916: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3917: #
3918: # Increase the access count for this resource in this child process
3919: #
1.281 www 3920: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3921: $accesshash{$key}++;
1.185 www 3922: }
1.349 www 3923:
1.361 www 3924: sub linklog {
3925: my ($from,$to)=@_;
3926: $from=&declutter($from);
3927: $to=&declutter($to);
3928: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3929: $accesshash{$to.'___'.$from.'___goto'}=1;
3930: }
1.1160 www 3931:
3932: sub statslog {
3933: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3934: if ($users<2) { return; }
3935: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3936: 'course' => $env{'request.course.id'},
3937: 'sections' => '"all"',
3938: 'num_students' => $users,
3939: 'part' => $part,
3940: 'symb' => $symb,
3941: 'mean_tries' => $av_attempts,
3942: 'deg_of_diff' => $degdiff});
3943: foreach my $key (keys(%dynstore)) {
3944: $accesshash{$key}=$dynstore{$key};
3945: }
3946: }
1.361 www 3947:
1.349 www 3948: sub userrolelog {
3949: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3950: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3951: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3952: $userrolehash
3953: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3954: =$tend.':'.$tstart;
1.662 raeburn 3955: }
1.1169 droeschl 3956: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3957: $userrolehash
3958: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3959: =$tend.':'.$tstart;
3960: }
1.1169 droeschl 3961: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3962: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3963: $domainrolehash
3964: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3965: = $tend.':'.$tstart;
3966: }
1.351 www 3967: }
3968:
1.957 raeburn 3969: sub courserolelog {
3970: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3971: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3972: my $cdom = $1;
3973: my $cnum = $2;
3974: my $sec = $3;
3975: my $namespace = 'rolelog';
3976: my %storehash = (
3977: role => $trole,
3978: start => $tstart,
3979: end => $tend,
3980: selfenroll => $selfenroll,
3981: context => $context,
3982: );
3983: if ($trole eq 'gr') {
3984: $namespace = 'groupslog';
3985: $storehash{'group'} = $sec;
3986: } else {
3987: $storehash{'section'} = $sec;
3988: }
3989: &write_log('course',$namespace,\%storehash,$delflag,$username,
3990: $domain,$cnum,$cdom);
3991: if (($trole ne 'st') || ($sec ne '')) {
3992: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3993: }
3994: }
3995: return;
3996: }
3997:
1.1172.2.9 raeburn 3998: sub domainrolelog {
3999: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4000: if ($area =~ m{^/($match_domain)/$}) {
4001: my $cdom = $1;
4002: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4003: my $namespace = 'rolelog';
4004: my %storehash = (
4005: role => $trole,
4006: start => $tstart,
4007: end => $tend,
4008: context => $context,
4009: );
4010: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4011: $domain,$domconfiguser,$cdom);
4012: }
4013: return;
4014:
4015: }
4016:
4017: sub coauthorrolelog {
4018: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4019: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4020: my $audom = $1;
4021: my $auname = $2;
4022: my $namespace = 'rolelog';
4023: my %storehash = (
4024: role => $trole,
4025: start => $tstart,
4026: end => $tend,
4027: context => $context,
4028: );
4029: &write_log('author',$namespace,\%storehash,$delflag,$username,
4030: $domain,$auname,$audom);
4031: }
4032: return;
4033: }
4034:
1.351 www 4035: sub get_course_adv_roles {
1.948 raeburn 4036: my ($cid,$codes) = @_;
1.620 albertel 4037: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4038: my %coursehash=&coursedescription($cid);
1.988 raeburn 4039: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4040: my %nothide=();
1.800 albertel 4041: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4042: if ($user !~ /:/) {
4043: $nothide{join(':',split(/[\@]/,$user))}=1;
4044: } else {
4045: $nothide{$user}=1;
4046: }
1.470 www 4047: }
1.1172.2.23 raeburn 4048: my @possdoms = ($coursehash{'domain'});
4049: if ($coursehash{'checkforpriv'}) {
4050: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4051: }
1.351 www 4052: my %returnhash=();
4053: my %dumphash=
4054: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4055: my $now=time;
1.997 raeburn 4056: my %privileged;
1.1000 raeburn 4057: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4058: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4059: if (($tstart) && ($tstart<0)) { next; }
4060: if (($tend) && ($tend<$now)) { next; }
4061: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4062: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4063: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4064: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4065: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4066: if ($role eq 'cr') { next; }
1.948 raeburn 4067: if ($codes) {
4068: if ($section) { $role .= ':'.$section; }
4069: if ($returnhash{$role}) {
4070: $returnhash{$role}.=','.$username.':'.$domain;
4071: } else {
4072: $returnhash{$role}=$username.':'.$domain;
4073: }
1.351 www 4074: } else {
1.988 raeburn 4075: my $key=&plaintext($role,$crstype);
1.973 bisitz 4076: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4077: if ($returnhash{$key}) {
4078: $returnhash{$key}.=','.$username.':'.$domain;
4079: } else {
4080: $returnhash{$key}=$username.':'.$domain;
4081: }
1.351 www 4082: }
1.948 raeburn 4083: }
1.400 www 4084: return %returnhash;
4085: }
4086:
4087: sub get_my_roles {
1.937 raeburn 4088: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4089: unless (defined($uname)) { $uname=$env{'user.name'}; }
4090: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4091: my (%dumphash,%nothide);
1.1086 raeburn 4092: if ($context eq 'userroles') {
1.1166 raeburn 4093: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4094: } else {
1.1172.2.23 raeburn 4095: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4096: if ($hidepriv) {
4097: my %coursehash=&coursedescription($udom.'_'.$uname);
4098: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4099: if ($user !~ /:/) {
4100: $nothide{join(':',split(/[\@]/,$user))} = 1;
4101: } else {
4102: $nothide{$user} = 1;
4103: }
4104: }
4105: }
1.858 raeburn 4106: }
1.400 www 4107: my %returnhash=();
4108: my $now=time;
1.999 raeburn 4109: my %privileged;
1.800 albertel 4110: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4111: my ($role,$tend,$tstart);
4112: if ($context eq 'userroles') {
1.1149 raeburn 4113: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4114: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4115: } else {
4116: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4117: }
1.400 www 4118: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4119: my $status = 'active';
1.939 raeburn 4120: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4121: $status = 'previous';
4122: }
4123: if (($tstart) && ($now<$tstart)) {
4124: $status = 'future';
4125: }
4126: if (ref($types) eq 'ARRAY') {
4127: if (!grep(/^\Q$status\E$/,@{$types})) {
4128: next;
4129: }
4130: } else {
4131: if ($status ne 'active') {
4132: next;
4133: }
4134: }
1.867 raeburn 4135: my ($rolecode,$username,$domain,$section,$area);
4136: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4137: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4138: (undef,$domain,$username,$section) = split(/\//,$area);
4139: } else {
4140: ($role,$username,$domain,$section) = split(/\:/,$entry);
4141: }
1.832 raeburn 4142: if (ref($roledoms) eq 'ARRAY') {
4143: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4144: next;
4145: }
4146: }
4147: if (ref($roles) eq 'ARRAY') {
4148: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4149: if ($role =~ /^cr\//) {
4150: if (!grep(/^cr$/,@{$roles})) {
4151: next;
4152: }
1.1104 raeburn 4153: } elsif ($role =~ /^gr\//) {
4154: if (!grep(/^gr$/,@{$roles})) {
4155: next;
4156: }
1.922 raeburn 4157: } else {
4158: next;
4159: }
1.832 raeburn 4160: }
1.867 raeburn 4161: }
1.937 raeburn 4162: if ($hidepriv) {
1.1172.2.23 raeburn 4163: my @privroles = ('dc','su');
1.999 raeburn 4164: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4165: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4166: } else {
1.1172.2.23 raeburn 4167: my $possdoms = [$domain];
4168: if (ref($roledoms) eq 'ARRAY') {
4169: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4170: }
1.1172.2.23 raeburn 4171: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4172: if (!$nothide{$username.':'.$domain}) {
4173: next;
4174: }
4175: }
1.937 raeburn 4176: }
4177: }
1.933 raeburn 4178: if ($withsec) {
4179: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4180: $tstart.':'.$tend;
4181: } else {
4182: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4183: }
1.832 raeburn 4184: }
1.373 www 4185: return %returnhash;
1.399 www 4186: }
4187:
4188: # ----------------------------------------------------- Frontpage Announcements
4189: #
4190: #
4191:
4192: sub postannounce {
4193: my ($server,$text)=@_;
1.844 albertel 4194: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4195: unless ($text=~/\w/) { $text=''; }
4196: return &reply('setannounce:'.&escape($text),$server);
4197: }
4198:
4199: sub getannounce {
1.448 albertel 4200:
4201: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4202: my $announcement='';
1.800 albertel 4203: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4204: close($fh);
1.399 www 4205: if ($announcement=~/\w/) {
4206: return
4207: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4208: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4209: } else {
4210: return '';
4211: }
4212: } else {
4213: return '';
4214: }
1.351 www 4215: }
1.353 www 4216:
4217: # ---------------------------------------------------------- Course ID routines
4218: # Deal with domain's nohist_courseid.db files
4219: #
4220:
4221: sub courseidput {
1.921 raeburn 4222: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4223: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4224: my $outcome;
4225: if ($caller eq 'timeonly') {
4226: my $cids = '';
4227: foreach my $item (keys(%$storehash)) {
4228: $cids.=&escape($item).'&';
4229: }
4230: $cids=~s/\&$//;
4231: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4232: $coursehome);
4233: } else {
4234: my $items = '';
4235: foreach my $item (keys(%$storehash)) {
4236: $items.= &escape($item).'='.
4237: &freeze_escape($$storehash{$item}).'&';
4238: }
4239: $items=~s/\&$//;
4240: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4241: $coursehome);
1.918 raeburn 4242: }
4243: if ($outcome eq 'unknown_cmd') {
4244: my $what;
4245: foreach my $cid (keys(%$storehash)) {
4246: $what .= &escape($cid).'=';
1.921 raeburn 4247: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4248: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4249: }
4250: $what =~ s/\:$/&/;
4251: }
4252: $what =~ s/\&$//;
4253: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4254: } else {
4255: return $outcome;
4256: }
1.353 www 4257: }
4258:
4259: sub courseiddump {
1.921 raeburn 4260: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4261: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4262: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4263: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4264: $hasuniquecode)=@_;
1.918 raeburn 4265: my $as_hash = 1;
4266: my %returnhash;
4267: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4268: my %libserv = &all_library();
4269: foreach my $tryserver (keys(%libserv)) {
4270: if ( ( $hostidflag == 1
4271: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4272: || (!defined($hostidflag)) ) {
4273:
1.918 raeburn 4274: if (($domfilter eq '') ||
4275: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4276: my $rep;
4277: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4278: $rep = &LONCAPA::Lond::dump_course_id_handler(
4279: join(":", (&host_domain($tryserver), $sincefilter,
4280: &escape($descfilter), &escape($instcodefilter),
4281: &escape($ownerfilter), &escape($coursefilter),
4282: &escape($typefilter), &escape($regexp_ok),
4283: $as_hash, &escape($selfenrollonly),
4284: &escape($catfilter), $showhidden, $caller,
4285: &escape($cloner), &escape($cc_clone), $cloneonly,
4286: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4287: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4288: } else {
4289: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4290: $sincefilter.':'.&escape($descfilter).':'.
4291: &escape($instcodefilter).':'.&escape($ownerfilter).
4292: ':'.&escape($coursefilter).':'.&escape($typefilter).
4293: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4294: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4295: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4296: &escape($cc_clone).':'.$cloneonly.':'.
4297: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4298: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4299: $tryserver);
4300: }
4301:
1.918 raeburn 4302: my @pairs=split(/\&/,$rep);
4303: foreach my $item (@pairs) {
4304: my ($key,$value)=split(/\=/,$item,2);
4305: $key = &unescape($key);
4306: next if ($key =~ /^error: 2 /);
4307: my $result = &thaw_unescape($value);
4308: if (ref($result) eq 'HASH') {
4309: $returnhash{$key}=$result;
4310: } else {
1.921 raeburn 4311: my @responses = split(/:/,$value);
4312: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4313: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4314: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4315: }
1.1008 raeburn 4316: }
1.353 www 4317: }
4318: }
4319: }
4320: }
4321: return %returnhash;
4322: }
4323:
1.1055 raeburn 4324: sub courselastaccess {
4325: my ($cdom,$cnum,$hostidref) = @_;
4326: my %returnhash;
4327: if ($cdom && $cnum) {
4328: my $chome = &homeserver($cnum,$cdom);
4329: if ($chome ne 'no_host') {
4330: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4331: &extract_lastaccess(\%returnhash,$rep);
4332: }
4333: } else {
4334: if (!$cdom) { $cdom=''; }
4335: my %libserv = &all_library();
4336: foreach my $tryserver (keys(%libserv)) {
4337: if (ref($hostidref) eq 'ARRAY') {
4338: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4339: }
4340: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4341: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4342: &extract_lastaccess(\%returnhash,$rep);
4343: }
4344: }
4345: }
4346: return %returnhash;
4347: }
4348:
4349: sub extract_lastaccess {
4350: my ($returnhash,$rep) = @_;
4351: if (ref($returnhash) eq 'HASH') {
4352: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4353: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4354: $rep eq '') {
4355: my @pairs=split(/\&/,$rep);
4356: foreach my $item (@pairs) {
4357: my ($key,$value)=split(/\=/,$item,2);
4358: $key = &unescape($key);
4359: next if ($key =~ /^error: 2 /);
4360: $returnhash->{$key} = &thaw_unescape($value);
4361: }
4362: }
4363: }
4364: return;
4365: }
4366:
1.658 raeburn 4367: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4368:
4369: sub dcmailput {
1.685 raeburn 4370: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4371: my $status = &Apache::lonnet::critical(
1.740 www 4372: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4373: &escape($message),$server);
1.662 raeburn 4374: return $status;
4375: }
4376:
1.658 raeburn 4377: sub dcmaildump {
4378: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4379: my %returnhash=();
1.846 albertel 4380:
4381: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4382: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4383: &escape($enddate).':';
4384: my @esc_senders=map { &escape($_)} @$senders;
4385: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4386: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4387: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4388: if (($key) && ($value)) {
4389: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4390: }
4391: }
4392: }
4393: return %returnhash;
4394: }
1.662 raeburn 4395: # ---------------------------------------------------------- Domain roles
4396:
4397: sub get_domain_roles {
4398: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4399: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4400: $startdate = '.';
4401: }
1.1018 raeburn 4402: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4403: $enddate = '.';
4404: }
1.922 raeburn 4405: my $rolelist;
4406: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4407: $rolelist = join('&',@{$roles});
1.922 raeburn 4408: }
1.662 raeburn 4409: my %personnel = ();
1.841 albertel 4410:
4411: my %servers = &get_servers($dom,'library');
4412: foreach my $tryserver (keys(%servers)) {
4413: %{$personnel{$tryserver}}=();
4414: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4415: &escape($startdate).':'.
4416: &escape($enddate).':'.
4417: &escape($rolelist), $tryserver))) {
4418: my ($key,$value) = split(/\=/,$line,2);
4419: if (($key) && ($value)) {
4420: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4421: }
4422: }
1.662 raeburn 4423: }
4424: return %personnel;
4425: }
1.658 raeburn 4426:
1.1057 www 4427: # ----------------------------------------------------------- Interval timing
1.149 www 4428:
1.1153 www 4429: {
4430: # Caches needed for speedup of navmaps
4431: # We don't want to cache this for very long at all (5 seconds at most)
4432: #
4433: # The user for whom we cache
4434: my $cachedkey='';
4435: # The cached times for this user
4436: my %cachedtimes=();
4437: # When this was last done
4438: my $cachedtime=();
4439:
4440: sub load_all_first_access {
1.1154 raeburn 4441: my ($uname,$udom)=@_;
1.1156 www 4442: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4443: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4444: return;
4445: }
4446: $cachedtime=time;
4447: $cachedkey=$uname.':'.$udom;
4448: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4449: }
4450:
1.504 albertel 4451: sub get_first_access {
1.1162 raeburn 4452: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4453: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4454: if ($argsymb) { $symb=$argsymb; }
4455: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4456: if ($argmap) { $map = $argmap; }
1.926 albertel 4457: if ($type eq 'course') {
4458: $res='course';
4459: } elsif ($type eq 'map') {
1.588 albertel 4460: $res=&symbread($map);
4461: } else {
4462: $res=$symb;
4463: }
1.1153 www 4464: &load_all_first_access($uname,$udom);
4465: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4466: }
4467:
4468: sub set_first_access {
1.1162 raeburn 4469: my ($type,$interval)=@_;
1.790 albertel 4470: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4471: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4472: if ($type eq 'course') {
4473: $res='course';
4474: } elsif ($type eq 'map') {
1.588 albertel 4475: $res=&symbread($map);
4476: } else {
4477: $res=$symb;
4478: }
1.1153 www 4479: $cachedkey='';
1.1162 raeburn 4480: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4481: if (!$firstaccess) {
1.1162 raeburn 4482: my $start = time;
4483: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4484: $udom,$uname);
4485: if ($putres eq 'ok') {
4486: &put('timerinterval',{"$courseid\0$res"=>$interval},
4487: $udom,$uname);
4488: &appenv(
4489: {
4490: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4491: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4492: }
4493: );
4494: }
4495: return $putres;
1.505 albertel 4496: }
4497: return 'already_set';
1.504 albertel 4498: }
1.1153 www 4499: }
1.1172.2.32 raeburn 4500:
4501: sub checkout {
4502: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4503: my $now=time;
4504: my $lonhost=$perlvar{'lonHostID'};
4505: my $infostr=&escape(
4506: 'CHECKOUTTOKEN&'.
4507: $tuname.'&'.
4508: $tudom.'&'.
4509: $tcrsid.'&'.
4510: $symb.'&'.
4511: $now.'&'.$ENV{'REMOTE_ADDR'});
4512: my $token=&reply('tmpput:'.$infostr,$lonhost);
4513: if ($token=~/^error\:/) {
4514: &logthis("<font color=\"blue\">WARNING: ".
4515: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4516: "</font>");
4517: return '';
4518: }
4519:
4520: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4521: $token=~tr/a-z/A-Z/;
4522:
4523: my %infohash=('resource.0.outtoken' => $token,
4524: 'resource.0.checkouttime' => $now,
4525: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4526:
4527: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4528: return '';
4529: } else {
4530: &logthis("<font color=\"blue\">WARNING: ".
4531: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4532: "</font>");
4533: }
4534:
4535: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4536: &escape('Checkout '.$infostr.' - '.
4537: $token)) ne 'ok') {
4538: return '';
4539: } else {
4540: &logthis("<font color=\"blue\">WARNING: ".
4541: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4542: "</font>");
4543: }
4544: return $token;
4545: }
4546:
4547: # ------------------------------------------------------------ Check in an item
4548:
4549: sub checkin {
4550: my $token=shift;
4551: my $now=time;
4552: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4553: $lonhost=~tr/A-Z/a-z/;
4554: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4555: $dtoken=~s/\W/\_/g;
4556: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4557: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4558:
4559: unless (($tuname) && ($tudom)) {
4560: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4561: return '';
4562: }
4563:
4564: unless (&allowed('mgr',$tcrsid)) {
4565: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4566: $env{'user.name'}.' - '.$env{'user.domain'});
4567: return '';
4568: }
4569:
4570: my %infohash=('resource.0.intoken' => $token,
4571: 'resource.0.checkintime' => $now,
4572: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4573:
4574: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4575: return '';
4576: }
4577:
4578: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4579: &escape('Checkin - '.$token)) ne 'ok') {
4580: return '';
4581: }
4582:
4583: return ($symb,$tuname,$tudom,$tcrsid);
4584: }
4585:
1.110 www 4586: # --------------------------------------------- Set Expire Date for Spreadsheet
4587:
4588: sub expirespread {
4589: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4590: my $cid=$env{'request.course.id'};
1.110 www 4591: if ($cid) {
4592: my $now=time;
4593: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4594: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4595: $env{'course.'.$cid.'.num'}.
1.110 www 4596: ':nohist_expirationdates:'.
4597: &escape($key).'='.$now,
1.620 albertel 4598: $env{'course.'.$cid.'.home'})
1.110 www 4599: }
4600: return 'ok';
1.14 www 4601: }
4602:
1.109 www 4603: # ----------------------------------------------------- Devalidate Spreadsheets
4604:
4605: sub devalidate {
1.325 www 4606: my ($symb,$uname,$udom)=@_;
1.620 albertel 4607: my $cid=$env{'request.course.id'};
1.109 www 4608: if ($cid) {
1.391 matthew 4609: # delete the stored spreadsheets for
4610: # - the student level sheet of this user in course's homespace
4611: # - the assessment level sheet for this resource
4612: # for this user in user's homespace
1.553 albertel 4613: # - current conditional state info
1.325 www 4614: my $key=$uname.':'.$udom.':';
1.109 www 4615: my $status=
1.299 matthew 4616: &del('nohist_calculatedsheets',
1.391 matthew 4617: [$key.'studentcalc:'],
1.620 albertel 4618: $env{'course.'.$cid.'.domain'},
4619: $env{'course.'.$cid.'.num'})
1.133 albertel 4620: .' '.
4621: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4622: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4623: unless ($status eq 'ok ok') {
4624: &logthis('Could not devalidate spreadsheet '.
1.325 www 4625: $uname.' at '.$udom.' for '.
1.109 www 4626: $symb.': '.$status);
1.133 albertel 4627: }
1.553 albertel 4628: &delenv('user.state.'.$cid);
1.109 www 4629: }
4630: }
4631:
1.265 albertel 4632: sub get_scalar {
4633: my ($string,$end) = @_;
4634: my $value;
4635: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4636: $value = $1;
4637: } elsif ($$string =~ s/^([^&]*?)&//) {
4638: $value = $1;
4639: }
4640: return &unescape($value);
4641: }
4642:
4643: sub array2str {
4644: my (@array) = @_;
4645: my $result=&arrayref2str(\@array);
4646: $result=~s/^__ARRAY_REF__//;
4647: $result=~s/__END_ARRAY_REF__$//;
4648: return $result;
4649: }
4650:
1.204 albertel 4651: sub arrayref2str {
4652: my ($arrayref) = @_;
1.265 albertel 4653: my $result='__ARRAY_REF__';
1.204 albertel 4654: foreach my $elem (@$arrayref) {
1.265 albertel 4655: if(ref($elem) eq 'ARRAY') {
4656: $result.=&arrayref2str($elem).'&';
4657: } elsif(ref($elem) eq 'HASH') {
4658: $result.=&hashref2str($elem).'&';
4659: } elsif(ref($elem)) {
4660: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4661: } else {
4662: $result.=&escape($elem).'&';
4663: }
4664: }
4665: $result=~s/\&$//;
1.265 albertel 4666: $result .= '__END_ARRAY_REF__';
1.204 albertel 4667: return $result;
4668: }
4669:
1.168 albertel 4670: sub hash2str {
1.204 albertel 4671: my (%hash) = @_;
4672: my $result=&hashref2str(\%hash);
1.265 albertel 4673: $result=~s/^__HASH_REF__//;
4674: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4675: return $result;
4676: }
4677:
4678: sub hashref2str {
4679: my ($hashref)=@_;
1.265 albertel 4680: my $result='__HASH_REF__';
1.800 albertel 4681: foreach my $key (sort(keys(%$hashref))) {
4682: if (ref($key) eq 'ARRAY') {
4683: $result.=&arrayref2str($key).'=';
4684: } elsif (ref($key) eq 'HASH') {
4685: $result.=&hashref2str($key).'=';
4686: } elsif (ref($key)) {
1.265 albertel 4687: $result.='=';
1.800 albertel 4688: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4689: } else {
1.1132 raeburn 4690: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4691: }
4692:
1.800 albertel 4693: if(ref($hashref->{$key}) eq 'ARRAY') {
4694: $result.=&arrayref2str($hashref->{$key}).'&';
4695: } elsif(ref($hashref->{$key}) eq 'HASH') {
4696: $result.=&hashref2str($hashref->{$key}).'&';
4697: } elsif(ref($hashref->{$key})) {
1.265 albertel 4698: $result.='&';
1.800 albertel 4699: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4700: } else {
1.800 albertel 4701: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4702: }
4703: }
1.168 albertel 4704: $result=~s/\&$//;
1.265 albertel 4705: $result .= '__END_HASH_REF__';
1.168 albertel 4706: return $result;
4707: }
4708:
4709: sub str2hash {
1.265 albertel 4710: my ($string)=@_;
4711: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4712: return %$hash;
4713: }
4714:
4715: sub str2hashref {
1.168 albertel 4716: my ($string) = @_;
1.265 albertel 4717:
4718: my %hash;
4719:
4720: if($string !~ /^__HASH_REF__/) {
4721: if (! ($string eq '' || !defined($string))) {
4722: $hash{'error'}='Not hash reference';
4723: }
4724: return (\%hash, $string);
4725: }
4726:
4727: $string =~ s/^__HASH_REF__//;
4728:
4729: while($string !~ /^__END_HASH_REF__/) {
4730: #key
4731: my $key='';
4732: if($string =~ /^__HASH_REF__/) {
4733: ($key, $string)=&str2hashref($string);
4734: if(defined($key->{'error'})) {
4735: $hash{'error'}='Bad data';
4736: return (\%hash, $string);
4737: }
4738: } elsif($string =~ /^__ARRAY_REF__/) {
4739: ($key, $string)=&str2arrayref($string);
4740: if($key->[0] eq 'Array reference error') {
4741: $hash{'error'}='Bad data';
4742: return (\%hash, $string);
4743: }
4744: } else {
4745: $string =~ s/^(.*?)=//;
1.267 albertel 4746: $key=&unescape($1);
1.265 albertel 4747: }
4748: $string =~ s/^=//;
4749:
4750: #value
4751: my $value='';
4752: if($string =~ /^__HASH_REF__/) {
4753: ($value, $string)=&str2hashref($string);
4754: if(defined($value->{'error'})) {
4755: $hash{'error'}='Bad data';
4756: return (\%hash, $string);
4757: }
4758: } elsif($string =~ /^__ARRAY_REF__/) {
4759: ($value, $string)=&str2arrayref($string);
4760: if($value->[0] eq 'Array reference error') {
4761: $hash{'error'}='Bad data';
4762: return (\%hash, $string);
4763: }
4764: } else {
4765: $value=&get_scalar(\$string,'__END_HASH_REF__');
4766: }
4767: $string =~ s/^&//;
4768:
4769: $hash{$key}=$value;
1.204 albertel 4770: }
1.265 albertel 4771:
4772: $string =~ s/^__END_HASH_REF__//;
4773:
4774: return (\%hash, $string);
1.204 albertel 4775: }
4776:
4777: sub str2array {
1.265 albertel 4778: my ($string)=@_;
4779: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4780: return @$array;
4781: }
4782:
4783: sub str2arrayref {
1.204 albertel 4784: my ($string) = @_;
1.265 albertel 4785: my @array;
4786:
4787: if($string !~ /^__ARRAY_REF__/) {
4788: if (! ($string eq '' || !defined($string))) {
4789: $array[0]='Array reference error';
4790: }
4791: return (\@array, $string);
4792: }
4793:
4794: $string =~ s/^__ARRAY_REF__//;
4795:
4796: while($string !~ /^__END_ARRAY_REF__/) {
4797: my $value='';
4798: if($string =~ /^__HASH_REF__/) {
4799: ($value, $string)=&str2hashref($string);
4800: if(defined($value->{'error'})) {
4801: $array[0] ='Array reference error';
4802: return (\@array, $string);
4803: }
4804: } elsif($string =~ /^__ARRAY_REF__/) {
4805: ($value, $string)=&str2arrayref($string);
4806: if($value->[0] eq 'Array reference error') {
4807: $array[0] ='Array reference error';
4808: return (\@array, $string);
4809: }
4810: } else {
4811: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4812: }
4813: $string =~ s/^&//;
4814:
4815: push(@array, $value);
1.191 harris41 4816: }
1.265 albertel 4817:
4818: $string =~ s/^__END_ARRAY_REF__//;
4819:
4820: return (\@array, $string);
1.168 albertel 4821: }
4822:
1.167 albertel 4823: # -------------------------------------------------------------------Temp Store
4824:
1.168 albertel 4825: sub tmpreset {
4826: my ($symb,$namespace,$domain,$stuname) = @_;
4827: if (!$symb) {
4828: $symb=&symbread();
1.620 albertel 4829: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4830: }
4831: $symb=escape($symb);
4832:
1.620 albertel 4833: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4834: $namespace=~s/\//\_/g;
4835: $namespace=~s/\W//g;
4836:
1.620 albertel 4837: if (!$domain) { $domain=$env{'user.domain'}; }
4838: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4839: if ($domain eq 'public' && $stuname eq 'public') {
4840: $stuname=$ENV{'REMOTE_ADDR'};
4841: }
1.1117 foxr 4842: my $path=LONCAPA::tempdir();
1.168 albertel 4843: my %hash;
4844: if (tie(%hash,'GDBM_File',
4845: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4846: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4847: foreach my $key (keys(%hash)) {
1.180 albertel 4848: if ($key=~ /:$symb/) {
1.168 albertel 4849: delete($hash{$key});
4850: }
4851: }
4852: }
4853: }
4854:
1.167 albertel 4855: sub tmpstore {
1.168 albertel 4856: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4857:
4858: if (!$symb) {
4859: $symb=&symbread();
1.620 albertel 4860: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4861: }
4862: $symb=escape($symb);
4863:
4864: if (!$namespace) {
4865: # I don't think we would ever want to store this for a course.
4866: # it seems this will only be used if we don't have a course.
1.620 albertel 4867: #$namespace=$env{'request.course.id'};
1.168 albertel 4868: #if (!$namespace) {
1.620 albertel 4869: $namespace=$env{'request.state'};
1.168 albertel 4870: #}
4871: }
4872: $namespace=~s/\//\_/g;
4873: $namespace=~s/\W//g;
1.620 albertel 4874: if (!$domain) { $domain=$env{'user.domain'}; }
4875: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4876: if ($domain eq 'public' && $stuname eq 'public') {
4877: $stuname=$ENV{'REMOTE_ADDR'};
4878: }
1.168 albertel 4879: my $now=time;
4880: my %hash;
1.1117 foxr 4881: my $path=LONCAPA::tempdir();
1.168 albertel 4882: if (tie(%hash,'GDBM_File',
4883: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4884: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4885: $hash{"version:$symb"}++;
4886: my $version=$hash{"version:$symb"};
4887: my $allkeys='';
4888: foreach my $key (keys(%$storehash)) {
4889: $allkeys.=$key.':';
1.591 albertel 4890: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4891: }
4892: $hash{"$version:$symb:timestamp"}=$now;
4893: $allkeys.='timestamp';
4894: $hash{"$version:keys:$symb"}=$allkeys;
4895: if (untie(%hash)) {
4896: return 'ok';
4897: } else {
4898: return "error:$!";
4899: }
4900: } else {
4901: return "error:$!";
4902: }
4903: }
1.167 albertel 4904:
1.168 albertel 4905: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4906:
1.168 albertel 4907: sub tmprestore {
4908: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4909:
1.168 albertel 4910: if (!$symb) {
4911: $symb=&symbread();
1.620 albertel 4912: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4913: }
4914: $symb=escape($symb);
4915:
1.620 albertel 4916: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4917:
1.620 albertel 4918: if (!$domain) { $domain=$env{'user.domain'}; }
4919: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4920: if ($domain eq 'public' && $stuname eq 'public') {
4921: $stuname=$ENV{'REMOTE_ADDR'};
4922: }
1.168 albertel 4923: my %returnhash;
4924: $namespace=~s/\//\_/g;
4925: $namespace=~s/\W//g;
4926: my %hash;
1.1117 foxr 4927: my $path=LONCAPA::tempdir();
1.168 albertel 4928: if (tie(%hash,'GDBM_File',
4929: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4930: &GDBM_READER(),0640)) {
1.168 albertel 4931: my $version=$hash{"version:$symb"};
4932: $returnhash{'version'}=$version;
4933: my $scope;
4934: for ($scope=1;$scope<=$version;$scope++) {
4935: my $vkeys=$hash{"$scope:keys:$symb"};
4936: my @keys=split(/:/,$vkeys);
4937: my $key;
4938: $returnhash{"$scope:keys"}=$vkeys;
4939: foreach $key (@keys) {
1.591 albertel 4940: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4941: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4942: }
4943: }
1.168 albertel 4944: if (!(untie(%hash))) {
4945: return "error:$!";
4946: }
4947: } else {
4948: return "error:$!";
4949: }
4950: return %returnhash;
1.167 albertel 4951: }
4952:
1.9 www 4953: # ----------------------------------------------------------------------- Store
4954:
4955: sub store {
1.124 www 4956: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4957: my $home='';
4958:
1.168 albertel 4959: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4960:
1.213 www 4961: $symb=&symbclean($symb);
1.122 albertel 4962: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4963:
1.620 albertel 4964: if (!$domain) { $domain=$env{'user.domain'}; }
4965: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4966:
4967: &devalidate($symb,$stuname,$domain);
1.109 www 4968:
4969: $symb=escape($symb);
1.187 www 4970: if (!$namespace) {
1.620 albertel 4971: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4972: return '';
4973: }
4974: }
1.620 albertel 4975: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4976:
4977: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4978: $$storehash{'host'}=$perlvar{'lonHostID'};
4979:
1.12 www 4980: my $namevalue='';
1.800 albertel 4981: foreach my $key (keys(%$storehash)) {
4982: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4983: }
1.12 www 4984: $namevalue=~s/\&$//;
1.187 www 4985: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4986: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4987: }
4988:
1.47 www 4989: # -------------------------------------------------------------- Critical Store
4990:
4991: sub cstore {
1.124 www 4992: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4993: my $home='';
4994:
1.168 albertel 4995: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4996:
1.213 www 4997: $symb=&symbclean($symb);
1.122 albertel 4998: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4999:
1.620 albertel 5000: if (!$domain) { $domain=$env{'user.domain'}; }
5001: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5002:
5003: &devalidate($symb,$stuname,$domain);
1.109 www 5004:
5005: $symb=escape($symb);
1.187 www 5006: if (!$namespace) {
1.620 albertel 5007: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5008: return '';
5009: }
5010: }
1.620 albertel 5011: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5012:
5013: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5014: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5015:
1.47 www 5016: my $namevalue='';
1.800 albertel 5017: foreach my $key (keys(%$storehash)) {
5018: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5019: }
1.47 www 5020: $namevalue=~s/\&$//;
1.187 www 5021: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5022: return critical
5023: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 5024: }
5025:
1.9 www 5026: # --------------------------------------------------------------------- Restore
5027:
5028: sub restore {
1.124 www 5029: my ($symb,$namespace,$domain,$stuname) = @_;
5030: my $home='';
5031:
1.168 albertel 5032: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5033:
1.122 albertel 5034: if (!$symb) {
1.1172.2.26 raeburn 5035: return if ($namespace eq 'courserequests');
5036: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5037: } else {
1.1172.2.26 raeburn 5038: unless ($namespace eq 'courserequests') {
5039: $symb=&escape(&symbclean($symb));
5040: }
1.122 albertel 5041: }
1.188 www 5042: if (!$namespace) {
1.620 albertel 5043: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5044: return '';
5045: }
5046: }
1.620 albertel 5047: if (!$domain) { $domain=$env{'user.domain'}; }
5048: if (!$stuname) { $stuname=$env{'user.name'}; }
5049: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5050: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5051:
1.12 www 5052: my %returnhash=();
1.800 albertel 5053: foreach my $line (split(/\&/,$answer)) {
5054: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5055: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5056: }
1.75 www 5057: my $version;
5058: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5059: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5060: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5061: }
1.75 www 5062: }
1.13 www 5063: return %returnhash;
1.34 www 5064: }
5065:
5066: # ---------------------------------------------------------- Course Description
1.1118 foxr 5067: #
5068: #
1.34 www 5069:
5070: sub coursedescription {
1.731 albertel 5071: my ($courseid,$args)=@_;
1.34 www 5072: $courseid=~s/^\///;
1.49 www 5073: $courseid=~s/\_/\//g;
1.34 www 5074: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5075: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5076: my $normalid=$cdomain.'_'.$cnum;
5077: # need to always cache even if we get errors otherwise we keep
5078: # trying and trying and trying to get the course description.
5079: my %envhash=();
5080: my %returnhash=();
1.731 albertel 5081:
5082: my $expiretime=600;
5083: if ($env{'request.course.id'} eq $normalid) {
5084: $expiretime=120;
5085: }
5086:
5087: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5088: if (!$args->{'freshen_cache'}
5089: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5090: foreach my $key (keys(%env)) {
5091: next if ($key !~ /^\Q$prefix\E(.*)/);
5092: my ($setting) = $1;
5093: $returnhash{$setting} = $env{$key};
5094: }
5095: return %returnhash;
5096: }
5097:
1.1118 foxr 5098: # get the data again
5099:
1.731 albertel 5100: if (!$args->{'one_time'}) {
5101: $envhash{'course.'.$normalid.'.last_cache'}=time;
5102: }
1.811 albertel 5103:
1.34 www 5104: if ($chome ne 'no_host') {
1.302 albertel 5105: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5106: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5107: my $username = $env{'user.name'}; # Defult username
5108: if(defined $args->{'user'}) {
5109: $username = $args->{'user'};
5110: }
1.129 albertel 5111: $returnhash{'home'}= $chome;
5112: $returnhash{'domain'} = $cdomain;
5113: $returnhash{'num'} = $cnum;
1.741 raeburn 5114: if (!defined($returnhash{'type'})) {
5115: $returnhash{'type'} = 'Course';
5116: }
1.130 albertel 5117: while (my ($name,$value) = each %returnhash) {
1.53 www 5118: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5119: }
1.270 www 5120: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5121: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5122: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5123: $envhash{'course.'.$normalid.'.home'}=$chome;
5124: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5125: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5126: }
5127: }
1.731 albertel 5128: if (!$args->{'one_time'}) {
1.949 raeburn 5129: &appenv(\%envhash);
1.731 albertel 5130: }
1.302 albertel 5131: return %returnhash;
1.461 www 5132: }
5133:
1.1080 raeburn 5134: sub update_released_required {
5135: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5136: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5137: $cid = $env{'request.course.id'};
5138: $cdom = $env{'course.'.$cid.'.domain'};
5139: $cnum = $env{'course.'.$cid.'.num'};
5140: $chome = $env{'course.'.$cid.'.home'};
5141: }
5142: if ($needsrelease) {
5143: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5144: my $needsupdate;
5145: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5146: $needsupdate = 1;
5147: } else {
5148: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5149: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5150: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5151: $needsupdate = 1;
5152: }
5153: }
5154: if ($needsupdate) {
5155: my %needshash = (
5156: 'internal.releaserequired' => $needsrelease,
5157: );
5158: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5159: if ($putresult eq 'ok') {
5160: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5161: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5162: if (ref($crsinfo{$cid}) eq 'HASH') {
5163: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5164: &courseidput($cdom,\%crsinfo,$chome,'notime');
5165: }
5166: }
5167: }
5168: }
5169: return;
5170: }
5171:
1.461 www 5172: # -------------------------------------------------See if a user is privileged
5173:
5174: sub privileged {
1.1172.2.23 raeburn 5175: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5176: my $now = time;
1.1172.2.23 raeburn 5177: my $roles;
5178: if (ref($possroles) eq 'ARRAY') {
5179: $roles = $possroles;
5180: } else {
5181: $roles = ['dc','su'];
5182: }
5183: if (ref($possdomains) eq 'ARRAY') {
5184: my %privileged = &privileged_by_domain($possdomains,$roles);
5185: foreach my $dom (@{$possdomains}) {
5186: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5187: (ref($privileged{$dom}) eq 'HASH')) {
5188: foreach my $role (@{$roles}) {
5189: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5190: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5191: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5192: return 1 unless (($end && $end < $now) ||
5193: ($start && $start > $now));
5194: }
5195: }
5196: }
5197: }
5198: }
5199: } else {
5200: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5201: my $now = time;
1.1170 droeschl 5202:
1.1172.2.58 raeburn 5203: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5204: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5205: if (grep(/^\Q$trole\E$/,@{$roles})) {
5206: return 1 unless ($tend && $tend < $now)
5207: or ($tstart && $tstart > $now);
1.1170 droeschl 5208: }
1.1172.2.23 raeburn 5209: }
5210: }
1.461 www 5211: return 0;
1.9 www 5212: }
1.1 albertel 5213:
1.1172.2.23 raeburn 5214: sub privileged_by_domain {
5215: my ($domains,$roles) = @_;
5216: my %privileged = ();
5217: my $cachetime = 60*60*24;
5218: my $now = time;
5219: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5220: return %privileged;
5221: }
5222: foreach my $dom (@{$domains}) {
5223: next if (ref($privileged{$dom}) eq 'HASH');
5224: my $needroles;
5225: foreach my $role (@{$roles}) {
5226: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5227: if (defined($cached)) {
5228: if (ref($result) eq 'HASH') {
5229: $privileged{$dom}{$role} = $result;
5230: }
5231: } else {
5232: $needroles = 1;
5233: }
5234: }
5235: if ($needroles) {
5236: my %dompersonnel = &get_domain_roles($dom,$roles);
5237: $privileged{$dom} = {};
5238: foreach my $server (keys(%dompersonnel)) {
5239: if (ref($dompersonnel{$server}) eq 'HASH') {
5240: foreach my $item (keys(%{$dompersonnel{$server}})) {
5241: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5242: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5243: next if ($end && $end < $now);
5244: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5245: $dompersonnel{$server}{$item};
5246: }
5247: }
5248: }
5249: if (ref($privileged{$dom}) eq 'HASH') {
5250: foreach my $role (@{$roles}) {
5251: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5252: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5253: } else {
5254: my %hash = ();
5255: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5256: }
5257: }
5258: }
5259: }
5260: }
5261: return %privileged;
5262: }
5263:
1.103 harris41 5264: # -------------------------------------------------------- Get user privileges
1.11 www 5265:
5266: sub rolesinit {
1.1169 droeschl 5267: my ($domain, $username) = @_;
5268: my %userroles = ('user.login.time' => time);
5269: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5270:
5271: # firstaccess and timerinterval are related to timed maps/resources.
5272: # also, blocking can be triggered by an activating timer
5273: # it's saved in the user's %env.
5274: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5275: my %timerinterval = &dump('timerinterval', $domain, $username);
5276: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5277: %timerintchk, %timerintenv);
5278:
1.1162 raeburn 5279: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5280: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5281: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5282: }
1.1169 droeschl 5283:
1.1162 raeburn 5284: foreach my $key (keys(%timerinterval)) {
5285: my ($cid,$rest) = split(/\0/,$key);
5286: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5287: }
1.1169 droeschl 5288:
1.11 www 5289: my %allroles=();
1.1162 raeburn 5290: my %allgroups=();
1.11 www 5291:
1.1172.2.58 raeburn 5292: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5293: my $role = $rolesdump{$area};
5294: $area =~ s/\_\w\w$//;
5295:
5296: my ($trole, $tend, $tstart, $group_privs);
5297:
5298: if ($role =~ /^cr/) {
5299: # Custom role, defined by a user
5300: # e.g., user.role.cr/msu/smith/mynewrole
5301: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5302: $trole = $1;
5303: ($tend, $tstart) = split('_', $2);
5304: } else {
5305: $trole = $role;
5306: }
5307: } elsif ($role =~ m|^gr/|) {
5308: # Role of member in a group, defined within a course/community
5309: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5310: ($trole, $tend, $tstart) = split(/_/, $role);
5311: next if $tstart eq '-1';
5312: ($trole, $group_privs) = split(/\//, $trole);
5313: $group_privs = &unescape($group_privs);
5314: } else {
5315: # Just a normal role, defined in roles.tab
5316: ($trole, $tend, $tstart) = split(/_/,$role);
5317: }
5318:
5319: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5320: $username);
5321: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5322:
5323: # role expired or not available yet?
5324: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5325: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5326:
5327: next if $area eq '' or $trole eq '';
5328:
5329: my $spec = "$trole.$area";
5330: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5331:
5332: if ($trole =~ /^cr\//) {
5333: # Custom role, defined by a user
5334: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5335: } elsif ($trole eq 'gr') {
5336: # Role of a member in a group, defined within a course/community
5337: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5338: next;
5339: } else {
5340: # Normal role, defined in roles.tab
5341: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5342: }
5343:
5344: my $cid = $tdomain.'_'.$trest;
5345: unless ($firstaccchk{$cid}) {
5346: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5347: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5348: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5349: $coursetimerstarts{$cid}{$item};
5350: }
5351: }
5352: $firstaccchk{$cid} = 1;
5353: }
5354: unless ($timerintchk{$cid}) {
5355: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5356: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5357: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5358: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5359: }
1.12 www 5360: }
1.1169 droeschl 5361: $timerintchk{$cid} = 1;
1.191 harris41 5362: }
1.11 www 5363: }
1.1169 droeschl 5364:
5365: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5366: \%allroles, \%allgroups);
5367: $env{'user.adv'} = $userroles{'user.adv'};
5368:
1.1162 raeburn 5369: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5370: }
5371:
1.567 raeburn 5372: sub set_arearole {
1.1172.2.19 raeburn 5373: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5374: unless ($nolog) {
1.567 raeburn 5375: # log the associated role with the area
1.1172.2.19 raeburn 5376: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5377: }
1.743 albertel 5378: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5379: }
5380:
5381: sub custom_roleprivs {
5382: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5383: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5384: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5385: if (&hostname($homsvr) ne '') {
1.567 raeburn 5386: my ($rdummy,$roledef)=
5387: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5388: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5389: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5390: if (defined($syspriv)) {
1.1043 raeburn 5391: if ($trest =~ /^$match_community$/) {
5392: $syspriv =~ s/bre\&S//;
5393: }
1.567 raeburn 5394: $$allroles{'cm./'}.=':'.$syspriv;
5395: $$allroles{$spec.'./'}.=':'.$syspriv;
5396: }
5397: if ($tdomain ne '') {
5398: if (defined($dompriv)) {
5399: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5400: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5401: }
5402: if (($trest ne '') && (defined($coursepriv))) {
5403: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5404: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5405: }
5406: }
5407: }
5408: }
5409: }
5410:
1.678 raeburn 5411: sub group_roleprivs {
5412: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5413: my $access = 1;
5414: my $now = time;
5415: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5416: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5417: if ($access) {
1.811 albertel 5418: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5419: $$allgroups{$course}{$group} .=':'.$group_privs;
5420: }
5421: }
1.567 raeburn 5422:
5423: sub standard_roleprivs {
5424: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5425: if (defined($pr{$trole.':s'})) {
5426: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5427: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5428: }
5429: if ($tdomain ne '') {
5430: if (defined($pr{$trole.':d'})) {
5431: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5432: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5433: }
5434: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5435: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5436: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5437: }
5438: }
5439: }
5440:
5441: sub set_userprivs {
1.1064 raeburn 5442: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5443: my $author=0;
5444: my $adv=0;
1.678 raeburn 5445: my %grouproles = ();
5446: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5447: my @groupkeys;
1.1000 raeburn 5448: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5449: push(@groupkeys,$role);
5450: }
5451: if (ref($groups_roles) eq 'HASH') {
5452: foreach my $key (keys(%{$groups_roles})) {
5453: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5454: push(@groupkeys,$key);
5455: }
5456: }
5457: }
5458: if (@groupkeys > 0) {
5459: foreach my $role (@groupkeys) {
5460: my ($trole,$area,$sec,$extendedarea);
5461: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5462: $trole = $1;
5463: $area = $2;
5464: $sec = $3;
5465: $extendedarea = $area.$sec;
5466: if (exists($$allgroups{$area})) {
5467: foreach my $group (keys(%{$$allgroups{$area}})) {
5468: my $spec = $trole.'.'.$extendedarea;
5469: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5470: $$allgroups{$area}{$group};
1.1064 raeburn 5471: }
1.678 raeburn 5472: }
5473: }
5474: }
5475: }
5476: }
1.800 albertel 5477: foreach my $group (keys(%grouproles)) {
5478: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5479: }
1.800 albertel 5480: foreach my $role (keys(%{$allroles})) {
5481: my %thesepriv;
1.941 raeburn 5482: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5483: foreach my $item (split(/:/,$$allroles{$role})) {
5484: if ($item ne '') {
5485: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5486: if ($restrictions eq '') {
5487: $thesepriv{$privilege}='F';
5488: } elsif ($thesepriv{$privilege} ne 'F') {
5489: $thesepriv{$privilege}.=$restrictions;
5490: }
5491: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5492: }
5493: }
5494: my $thesestr='';
1.1104 raeburn 5495: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5496: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5497: }
5498: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5499: }
5500: return ($author,$adv);
5501: }
5502:
1.994 raeburn 5503: sub role_status {
1.1104 raeburn 5504: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5505: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5506: my ($one,$two) = split(m{\./},$rolekey,2);
5507: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5508: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5509: $$where = '/'.$two;
1.994 raeburn 5510: $$trolecode=$$role.'.'.$$where;
5511: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5512: $$tstatus='is';
1.1104 raeburn 5513: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5514: $$tstatus='future';
1.1034 raeburn 5515: if ($$tstart<$now) {
5516: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5517: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5518: my (%allroles,%allgroups,$group_privs,
5519: %groups_roles,@rolecodes);
1.1002 raeburn 5520: my %userroles = (
5521: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5522: );
1.1064 raeburn 5523: @rolecodes = ('cm');
1.1002 raeburn 5524: my $spec=$$role.'.'.$$where;
5525: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5526: if ($$role =~ /^cr\//) {
5527: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5528: push(@rolecodes,'cr');
1.1002 raeburn 5529: } elsif ($$role eq 'gr') {
1.1064 raeburn 5530: push(@rolecodes,$$role);
1.1002 raeburn 5531: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5532: $env{'user.name'});
1.1064 raeburn 5533: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5534: (undef,my $group_privs) = split(/\//,$trole);
5535: $group_privs = &unescape($group_privs);
5536: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5537: 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 5538: &get_groups_roles($tdomain,$trest,
5539: \%course_roles,\@rolecodes,
5540: \%groups_roles);
1.1002 raeburn 5541: } else {
1.1064 raeburn 5542: push(@rolecodes,$$role);
1.1002 raeburn 5543: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5544: }
1.1064 raeburn 5545: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5546: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5547: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5548: }
5549: }
1.1034 raeburn 5550: $$tstatus = 'is';
1.1002 raeburn 5551: }
1.994 raeburn 5552: }
5553: if ($$tend) {
1.1104 raeburn 5554: if ($$tend<$update) {
1.994 raeburn 5555: $$tstatus='expired';
5556: } elsif ($$tend<$now) {
5557: $$tstatus='will_not';
5558: }
5559: }
5560: }
5561: }
5562: }
5563:
1.1104 raeburn 5564: sub get_groups_roles {
5565: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5566: return unless((ref($cdom_courseroles) eq 'HASH') &&
5567: (ref($rolecodes) eq 'ARRAY') &&
5568: (ref($groups_roles) eq 'HASH'));
5569: if (keys(%{$cdom_courseroles}) > 0) {
5570: my ($cnum) = ($rest =~ /^($match_courseid)/);
5571: if ($cdom ne '' && $cnum ne '') {
5572: foreach my $key (keys(%{$cdom_courseroles})) {
5573: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5574: my $crsrole = $1;
5575: my $crssec = $2;
5576: if ($crsrole =~ /^cr/) {
5577: unless (grep(/^cr$/,@{$rolecodes})) {
5578: push(@{$rolecodes},'cr');
5579: }
5580: } else {
5581: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5582: push(@{$rolecodes},$crsrole);
5583: }
5584: }
5585: my $rolekey = "$crsrole./$cdom/$cnum";
5586: if ($crssec ne '') {
5587: $rolekey .= "/$crssec";
5588: }
5589: $rolekey .= './';
5590: $groups_roles->{$rolekey} = $rolecodes;
5591: }
5592: }
5593: }
5594: }
5595: return;
5596: }
5597:
5598: sub delete_env_groupprivs {
5599: my ($where,$courseroles,$possroles) = @_;
5600: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5601: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5602: unless (ref($courseroles->{$udom}) eq 'HASH') {
5603: %{$courseroles->{$udom}} =
5604: &get_my_roles('','','userroles',['active'],
5605: $possroles,[$udom],1);
5606: }
5607: if (ref($courseroles->{$udom}) eq 'HASH') {
5608: foreach my $item (keys(%{$courseroles->{$udom}})) {
5609: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5610: my $area = '/'.$cdom.'/'.$cnum;
5611: my $privkey = "user.priv.$crsrole.$area";
5612: if ($crssec ne '') {
5613: $privkey .= '/'.$crssec;
5614: }
5615: $privkey .= ".$area/$group";
5616: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5617: }
5618: }
5619: return;
5620: }
5621:
1.994 raeburn 5622: sub check_adhoc_privs {
1.1104 raeburn 5623: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5624: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5625: my $setprivs;
1.994 raeburn 5626: if ($env{$cckey}) {
5627: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5628: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5629: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5630: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5631: $setprivs = 1;
1.994 raeburn 5632: }
5633: } else {
1.1088 raeburn 5634: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5635: $setprivs = 1;
1.994 raeburn 5636: }
1.1172.2.9 raeburn 5637: return $setprivs;
1.994 raeburn 5638: }
5639:
5640: sub set_adhoc_privileges {
5641: # role can be cc or ca
1.1088 raeburn 5642: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5643: my $area = '/'.$dcdom.'/'.$pickedcourse;
5644: my $spec = $role.'.'.$area;
5645: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5646: $env{'user.name'},1);
1.994 raeburn 5647: my %ccrole = ();
5648: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5649: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5650: &appenv(\%userroles,[$role,'cm']);
5651: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5652: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5653: &appenv( {'request.role' => $spec,
5654: 'request.role.domain' => $dcdom,
5655: 'request.course.sec' => ''
5656: }
5657: );
5658: my $tadv=0;
5659: if (&allowed('adv') eq 'F') { $tadv=1; }
5660: &appenv({'request.role.adv' => $tadv});
5661: }
1.994 raeburn 5662: }
5663:
1.12 www 5664: # --------------------------------------------------------------- get interface
5665:
5666: sub get {
1.131 albertel 5667: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5668: my $items='';
1.800 albertel 5669: foreach my $item (@$storearr) {
5670: $items.=&escape($item).'&';
1.191 harris41 5671: }
1.12 www 5672: $items=~s/\&$//;
1.620 albertel 5673: if (!$udomain) { $udomain=$env{'user.domain'}; }
5674: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5675: my $uhome=&homeserver($uname,$udomain);
5676:
1.133 albertel 5677: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5678: my @pairs=split(/\&/,$rep);
1.273 albertel 5679: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5680: return @pairs;
5681: }
1.15 www 5682: my %returnhash=();
1.42 www 5683: my $i=0;
1.800 albertel 5684: foreach my $item (@$storearr) {
5685: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5686: $i++;
1.191 harris41 5687: }
1.15 www 5688: return %returnhash;
1.27 www 5689: }
5690:
5691: # --------------------------------------------------------------- del interface
5692:
5693: sub del {
1.133 albertel 5694: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5695: my $items='';
1.800 albertel 5696: foreach my $item (@$storearr) {
5697: $items.=&escape($item).'&';
1.191 harris41 5698: }
1.984 neumanie 5699:
1.27 www 5700: $items=~s/\&$//;
1.620 albertel 5701: if (!$udomain) { $udomain=$env{'user.domain'}; }
5702: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5703: my $uhome=&homeserver($uname,$udomain);
5704: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5705: }
5706:
5707: # -------------------------------------------------------------- dump interface
5708:
1.1172.2.22 raeburn 5709: sub unserialize {
5710: my ($rep, $escapedkeys) = @_;
5711:
5712: return {} if $rep =~ /^error/;
5713:
5714: my %returnhash=();
5715: foreach my $item (split(/\&/,$rep)) {
5716: my ($key, $value) = split(/=/, $item, 2);
5717: $key = unescape($key) unless $escapedkeys;
5718: next if $key =~ /^error: 2 /;
5719: $returnhash{$key} = &thaw_unescape($value);
5720: }
5721: return \%returnhash;
5722: }
5723:
5724: # see Lond::dump_with_regexp
5725: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5726: sub dump {
1.1172.2.22 raeburn 5727: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5728: if (!$udomain) { $udomain=$env{'user.domain'}; }
5729: if (!$uname) { $uname=$env{'user.name'}; }
5730: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5731:
1.1172.2.55 raeburn 5732: if ($regexp) {
5733: $regexp=&escape($regexp);
5734: } else {
5735: $regexp='.';
5736: }
1.1172.2.22 raeburn 5737: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5738: # user is hosted on this machine
1.1172.2.55 raeburn 5739: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5740: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5741: return %{&unserialize($reply, $escapedkeys)};
5742: }
1.1166 raeburn 5743: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5744: my @pairs=split(/\&/,$rep);
5745: my %returnhash=();
1.1098 foxr 5746: if (!($rep =~ /^error/ )) {
5747: foreach my $item (@pairs) {
5748: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5749: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5750: next if ($key =~ /^error: 2 /);
5751: $returnhash{$key}=&thaw_unescape($value);
5752: }
1.755 albertel 5753: }
5754: return %returnhash;
1.407 www 5755: }
5756:
1.1098 foxr 5757:
1.717 albertel 5758: # --------------------------------------------------------- dumpstore interface
5759:
5760: sub dumpstore {
5761: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5762: # same as dump but keys must be escaped. They may contain colon separated
5763: # lists of values that may themself contain colons (e.g. symbs).
5764: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5765: }
5766:
1.407 www 5767: # -------------------------------------------------------------- keys interface
5768:
5769: sub getkeys {
5770: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5771: if (!$udomain) { $udomain=$env{'user.domain'}; }
5772: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5773: my $uhome=&homeserver($uname,$udomain);
5774: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5775: my @keyarray=();
1.800 albertel 5776: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5777: next if ($key =~ /^error: 2 /);
1.800 albertel 5778: push(@keyarray,&unescape($key));
1.407 www 5779: }
5780: return @keyarray;
1.318 matthew 5781: }
5782:
1.319 matthew 5783: # --------------------------------------------------------------- currentdump
5784: sub currentdump {
1.328 matthew 5785: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5786: $courseid = $env{'request.course.id'} if (! defined($courseid));
5787: $sdom = $env{'user.domain'} if (! defined($sdom));
5788: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5789: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5790: my $rep;
5791:
5792: if (grep { $_ eq $uhome } current_machine_ids()) {
5793: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5794: $courseid)));
5795: } else {
5796: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5797: }
5798:
1.318 matthew 5799: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5800: #
1.318 matthew 5801: my %returnhash=();
1.319 matthew 5802: #
5803: if ($rep eq "unknown_cmd") {
5804: # an old lond will not know currentdump
5805: # Do a dump and make it look like a currentdump
1.822 albertel 5806: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5807: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5808: my %hash = @tmp;
5809: @tmp=();
1.424 matthew 5810: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5811: } else {
5812: my @pairs=split(/\&/,$rep);
1.800 albertel 5813: foreach my $pair (@pairs) {
5814: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5815: my ($symb,$param) = split(/:/,$key);
5816: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5817: &thaw_unescape($value);
1.319 matthew 5818: }
1.191 harris41 5819: }
1.12 www 5820: return %returnhash;
1.424 matthew 5821: }
5822:
5823: sub convert_dump_to_currentdump{
5824: my %hash = %{shift()};
5825: my %returnhash;
5826: # Code ripped from lond, essentially. The only difference
5827: # here is the unescaping done by lonnet::dump(). Conceivably
5828: # we might run in to problems with parameter names =~ /^v\./
5829: while (my ($key,$value) = each(%hash)) {
5830: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5831: $symb = &unescape($symb);
5832: $param = &unescape($param);
1.424 matthew 5833: next if ($v eq 'version' || $symb eq 'keys');
5834: next if (exists($returnhash{$symb}) &&
5835: exists($returnhash{$symb}->{$param}) &&
5836: $returnhash{$symb}->{'v.'.$param} > $v);
5837: $returnhash{$symb}->{$param}=$value;
5838: $returnhash{$symb}->{'v.'.$param}=$v;
5839: }
5840: #
5841: # Remove all of the keys in the hashes which keep track of
5842: # the version of the parameter.
5843: while (my ($symb,$param_hash) = each(%returnhash)) {
5844: # use a foreach because we are going to delete from the hash.
5845: foreach my $key (keys(%$param_hash)) {
5846: delete($param_hash->{$key}) if ($key =~ /^v\./);
5847: }
5848: }
5849: return \%returnhash;
1.12 www 5850: }
5851:
1.627 albertel 5852: # ------------------------------------------------------ critical inc interface
5853:
5854: sub cinc {
5855: return &inc(@_,'critical');
5856: }
5857:
1.449 matthew 5858: # --------------------------------------------------------------- inc interface
5859:
5860: sub inc {
1.627 albertel 5861: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5862: if (!$udomain) { $udomain=$env{'user.domain'}; }
5863: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5864: my $uhome=&homeserver($uname,$udomain);
5865: my $items='';
5866: if (! ref($store)) {
5867: # got a single value, so use that instead
5868: $items = &escape($store).'=&';
5869: } elsif (ref($store) eq 'SCALAR') {
5870: $items = &escape($$store).'=&';
5871: } elsif (ref($store) eq 'ARRAY') {
5872: $items = join('=&',map {&escape($_);} @{$store});
5873: } elsif (ref($store) eq 'HASH') {
5874: while (my($key,$value) = each(%{$store})) {
5875: $items.= &escape($key).'='.&escape($value).'&';
5876: }
5877: }
5878: $items=~s/\&$//;
1.627 albertel 5879: if ($critical) {
5880: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5881: } else {
5882: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5883: }
1.449 matthew 5884: }
5885:
1.12 www 5886: # --------------------------------------------------------------- put interface
5887:
5888: sub put {
1.134 albertel 5889: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5890: if (!$udomain) { $udomain=$env{'user.domain'}; }
5891: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5892: my $uhome=&homeserver($uname,$udomain);
1.12 www 5893: my $items='';
1.800 albertel 5894: foreach my $item (keys(%$storehash)) {
5895: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5896: }
1.12 www 5897: $items=~s/\&$//;
1.134 albertel 5898: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5899: }
5900:
1.631 albertel 5901: # ------------------------------------------------------------ newput interface
5902:
5903: sub newput {
5904: my ($namespace,$storehash,$udomain,$uname)=@_;
5905: if (!$udomain) { $udomain=$env{'user.domain'}; }
5906: if (!$uname) { $uname=$env{'user.name'}; }
5907: my $uhome=&homeserver($uname,$udomain);
5908: my $items='';
5909: foreach my $key (keys(%$storehash)) {
5910: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5911: }
5912: $items=~s/\&$//;
5913: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5914: }
5915:
5916: # --------------------------------------------------------- putstore interface
5917:
1.524 raeburn 5918: sub putstore {
1.1172.2.59 raeburn 5919: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5920: if (!$udomain) { $udomain=$env{'user.domain'}; }
5921: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5922: my $uhome=&homeserver($uname,$udomain);
5923: my $items='';
1.715 albertel 5924: foreach my $key (keys(%$storehash)) {
5925: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5926: }
1.715 albertel 5927: $items=~s/\&$//;
1.716 albertel 5928: my $esc_symb=&escape($symb);
5929: my $esc_v=&escape($version);
1.715 albertel 5930: my $reply =
1.716 albertel 5931: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5932: $uhome);
1.1172.2.59 raeburn 5933: if (($tolog) && ($reply eq 'ok')) {
5934: my $namevalue='';
5935: foreach my $key (keys(%{$storehash})) {
5936: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5937: }
5938: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5939: '&host='.&escape($perlvar{'lonHostID'}).
5940: '&version='.$esc_v.
5941: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5942: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5943: }
1.715 albertel 5944: if ($reply eq 'unknown_cmd') {
1.716 albertel 5945: # gfall back to way things use to be done
1.715 albertel 5946: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5947: $uname);
1.524 raeburn 5948: }
1.715 albertel 5949: return $reply;
5950: }
5951:
5952: sub old_putstore {
1.716 albertel 5953: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5954: if (!$udomain) { $udomain=$env{'user.domain'}; }
5955: if (!$uname) { $uname=$env{'user.name'}; }
5956: my $uhome=&homeserver($uname,$udomain);
5957: my %newstorehash;
1.800 albertel 5958: foreach my $item (keys(%$storehash)) {
5959: my $key = $version.':'.&escape($symb).':'.$item;
5960: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5961: }
5962: my $items='';
5963: my %allitems = ();
1.800 albertel 5964: foreach my $item (keys(%newstorehash)) {
5965: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5966: my $key = $1.':keys:'.$2;
5967: $allitems{$key} .= $3.':';
5968: }
1.800 albertel 5969: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5970: }
1.800 albertel 5971: foreach my $item (keys(%allitems)) {
5972: $allitems{$item} =~ s/\:$//;
5973: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5974: }
5975: $items=~s/\&$//;
5976: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5977: }
5978:
1.47 www 5979: # ------------------------------------------------------ critical put interface
5980:
5981: sub cput {
1.134 albertel 5982: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5983: if (!$udomain) { $udomain=$env{'user.domain'}; }
5984: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5985: my $uhome=&homeserver($uname,$udomain);
1.47 www 5986: my $items='';
1.800 albertel 5987: foreach my $item (keys(%$storehash)) {
5988: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5989: }
1.47 www 5990: $items=~s/\&$//;
1.134 albertel 5991: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5992: }
5993:
5994: # -------------------------------------------------------------- eget interface
5995:
5996: sub eget {
1.133 albertel 5997: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5998: my $items='';
1.800 albertel 5999: foreach my $item (@$storearr) {
6000: $items.=&escape($item).'&';
1.191 harris41 6001: }
1.12 www 6002: $items=~s/\&$//;
1.620 albertel 6003: if (!$udomain) { $udomain=$env{'user.domain'}; }
6004: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6005: my $uhome=&homeserver($uname,$udomain);
6006: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6007: my @pairs=split(/\&/,$rep);
6008: my %returnhash=();
1.42 www 6009: my $i=0;
1.800 albertel 6010: foreach my $item (@$storearr) {
6011: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6012: $i++;
1.191 harris41 6013: }
1.12 www 6014: return %returnhash;
6015: }
6016:
1.667 albertel 6017: # ------------------------------------------------------------ tmpput interface
6018: sub tmpput {
1.802 raeburn 6019: my ($storehash,$server,$context)=@_;
1.667 albertel 6020: my $items='';
1.800 albertel 6021: foreach my $item (keys(%$storehash)) {
6022: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6023: }
6024: $items=~s/\&$//;
1.802 raeburn 6025: if (defined($context)) {
6026: $items .= ':'.&escape($context);
6027: }
1.667 albertel 6028: return &reply("tmpput:$items",$server);
6029: }
6030:
6031: # ------------------------------------------------------------ tmpget interface
6032: sub tmpget {
1.688 albertel 6033: my ($token,$server)=@_;
6034: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6035: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6036: my %returnhash;
6037: foreach my $item (split(/\&/,$rep)) {
6038: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6039: next if ($key =~ /^error: 2 /);
1.667 albertel 6040: $returnhash{&unescape($key)}=&thaw_unescape($value);
6041: }
6042: return %returnhash;
6043: }
6044:
1.1113 raeburn 6045: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6046: sub tmpdel {
6047: my ($token,$server)=@_;
6048: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6049: return &reply("tmpdel:$token",$server);
6050: }
6051:
1.1172.2.13 raeburn 6052: # ------------------------------------------------------------ get_timebased_id
6053:
6054: sub get_timebased_id {
6055: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6056: $maxtries) = @_;
6057: my ($newid,$error,$dellock);
6058: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6059: return ('','ok','invalid call to get suffix');
6060: }
6061:
6062: # set defaults for any optional args for which values were not supplied
6063: if ($who eq '') {
6064: $who = $env{'user.name'}.':'.$env{'user.domain'};
6065: }
6066: if (!$locktries) {
6067: $locktries = 3;
6068: }
6069: if (!$maxtries) {
6070: $maxtries = 10;
6071: }
6072:
6073: if (($cdom eq '') || ($cnum eq '')) {
6074: if ($env{'request.course.id'}) {
6075: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6076: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6077: }
6078: if (($cdom eq '') || ($cnum eq '')) {
6079: return ('','ok','call to get suffix not in course context');
6080: }
6081: }
6082:
6083: # construct locking item
6084: my $lockhash = {
6085: $prefix."\0".'locked_'.$keyid => $who,
6086: };
6087: my $tries = 0;
6088:
6089: # attempt to get lock on nohist_$namespace file
6090: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6091: while (($gotlock ne 'ok') && $tries <$locktries) {
6092: $tries ++;
6093: sleep 1;
6094: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6095: }
6096:
6097: # attempt to get unique identifier, based on current timestamp
6098: if ($gotlock eq 'ok') {
6099: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6100: my $id = time;
6101: $newid = $id;
1.1172.2.56 raeburn 6102: if ($idtype eq 'addcode') {
6103: $newid .= &sixnum_code();
6104: }
1.1172.2.13 raeburn 6105: my $idtries = 0;
6106: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6107: if ($idtype eq 'concat') {
6108: $newid = $id.$idtries;
1.1172.2.56 raeburn 6109: } elsif ($idtype eq 'addcode') {
6110: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6111: } else {
6112: $newid ++;
6113: }
6114: $idtries ++;
6115: }
6116: if (!exists($inuse{$prefix."\0".$newid})) {
6117: my %new_item = (
6118: $prefix."\0".$newid => $who,
6119: );
6120: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6121: $cdom,$cnum);
6122: if ($putresult ne 'ok') {
6123: undef($newid);
6124: $error = 'error saving new item: '.$putresult;
6125: }
6126: } else {
1.1172.2.56 raeburn 6127: undef($newid);
1.1172.2.13 raeburn 6128: $error = ('error: no unique suffix available for the new item ');
6129: }
6130: # remove lock
6131: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6132: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6133: } else {
6134: $error = "error: could not obtain lockfile\n";
6135: $dellock = 'ok';
1.1172.2.58 raeburn 6136: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6137: $dellock = 'nolock';
6138: }
1.1172.2.13 raeburn 6139: }
6140: return ($newid,$dellock,$error);
6141: }
6142:
1.1172.2.56 raeburn 6143: sub sixnum_code {
6144: my $code;
6145: for (0..6) {
6146: $code .= int( rand(9) );
6147: }
6148: return $code;
6149: }
6150:
1.765 albertel 6151: # -------------------------------------------------- portfolio access checking
6152:
6153: sub portfolio_access {
1.766 albertel 6154: my ($requrl) = @_;
1.765 albertel 6155: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6156: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6157: if ($result) {
6158: my %setters;
6159: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6160: my ($startblock,$endblock) =
6161: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6162: if ($startblock && $endblock) {
6163: return 'B';
6164: }
6165: } else {
6166: my ($startblock,$endblock) =
6167: &Apache::loncommon::blockcheck(\%setters,'port');
6168: if ($startblock && $endblock) {
6169: return 'B';
6170: }
6171: }
6172: }
1.765 albertel 6173: if ($result eq 'ok') {
1.766 albertel 6174: return 'F';
1.765 albertel 6175: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6176: return 'A';
1.765 albertel 6177: }
1.766 albertel 6178: return '';
1.765 albertel 6179: }
6180:
6181: sub get_portfolio_access {
1.767 albertel 6182: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6183:
6184: if (!ref($access_hash)) {
6185: my $current_perms = &get_portfile_permissions($udom,$unum);
6186: my %access_controls = &get_access_controls($current_perms,$group,
6187: $file_name);
6188: $access_hash = $access_controls{$file_name};
6189: }
6190:
1.765 albertel 6191: my ($public,$guest,@domains,@users,@courses,@groups);
6192: my $now = time;
6193: if (ref($access_hash) eq 'HASH') {
6194: foreach my $key (keys(%{$access_hash})) {
6195: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6196: if ($start > $now) {
6197: next;
6198: }
6199: if ($end && $end<$now) {
6200: next;
6201: }
6202: if ($scope eq 'public') {
6203: $public = $key;
6204: last;
6205: } elsif ($scope eq 'guest') {
6206: $guest = $key;
6207: } elsif ($scope eq 'domains') {
6208: push(@domains,$key);
6209: } elsif ($scope eq 'users') {
6210: push(@users,$key);
6211: } elsif ($scope eq 'course') {
6212: push(@courses,$key);
6213: } elsif ($scope eq 'group') {
6214: push(@groups,$key);
6215: }
6216: }
6217: if ($public) {
6218: return 'ok';
6219: }
6220: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6221: if ($guest) {
6222: return $guest;
6223: }
6224: } else {
6225: if (@domains > 0) {
6226: foreach my $domkey (@domains) {
6227: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6228: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6229: return 'ok';
6230: }
6231: }
6232: }
6233: }
6234: if (@users > 0) {
6235: foreach my $userkey (@users) {
1.865 raeburn 6236: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6237: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6238: if (ref($item) eq 'HASH') {
6239: if (($item->{'uname'} eq $env{'user.name'}) &&
6240: ($item->{'udom'} eq $env{'user.domain'})) {
6241: return 'ok';
6242: }
6243: }
6244: }
6245: }
1.765 albertel 6246: }
6247: }
6248: my %roleshash;
6249: my @courses_and_groups = @courses;
6250: push(@courses_and_groups,@groups);
6251: if (@courses_and_groups > 0) {
6252: my (%allgroups,%allroles);
6253: my ($start,$end,$role,$sec,$group);
6254: foreach my $envkey (%env) {
1.1060 raeburn 6255: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6256: my $cid = $2.'_'.$3;
6257: if ($1 eq 'gr') {
6258: $group = $4;
6259: $allgroups{$cid}{$group} = $env{$envkey};
6260: } else {
6261: if ($4 eq '') {
6262: $sec = 'none';
6263: } else {
6264: $sec = $4;
6265: }
6266: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6267: }
1.811 albertel 6268: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6269: my $cid = $2.'_'.$3;
6270: if ($4 eq '') {
6271: $sec = 'none';
6272: } else {
6273: $sec = $4;
6274: }
6275: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6276: }
6277: }
6278: if (keys(%allroles) == 0) {
6279: return;
6280: }
6281: foreach my $key (@courses_and_groups) {
6282: my %content = %{$$access_hash{$key}};
6283: my $cnum = $content{'number'};
6284: my $cdom = $content{'domain'};
6285: my $cid = $cdom.'_'.$cnum;
6286: if (!exists($allroles{$cid})) {
6287: next;
6288: }
6289: foreach my $role_id (keys(%{$content{'roles'}})) {
6290: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6291: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6292: my @status = @{$content{'roles'}{$role_id}{'access'}};
6293: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6294: foreach my $role (keys(%{$allroles{$cid}})) {
6295: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6296: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6297: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6298: if (grep/^all$/,@sections) {
6299: return 'ok';
6300: } else {
6301: if (grep/^$sec$/,@sections) {
6302: return 'ok';
6303: }
6304: }
6305: }
6306: }
6307: if (keys(%{$allgroups{$cid}}) == 0) {
6308: if (grep/^none$/,@groups) {
6309: return 'ok';
6310: }
6311: } else {
6312: if (grep/^all$/,@groups) {
6313: return 'ok';
6314: }
6315: foreach my $group (keys(%{$allgroups{$cid}})) {
6316: if (grep/^$group$/,@groups) {
6317: return 'ok';
6318: }
6319: }
6320: }
6321: }
6322: }
6323: }
6324: }
6325: }
6326: if ($guest) {
6327: return $guest;
6328: }
6329: }
6330: }
6331: return;
6332: }
6333:
6334: sub course_group_datechecker {
6335: my ($dates,$now,$status) = @_;
6336: my ($start,$end) = split(/\./,$dates);
6337: if (!$start && !$end) {
6338: return 'ok';
6339: }
6340: if (grep/^active$/,@{$status}) {
6341: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6342: return 'ok';
6343: }
6344: }
6345: if (grep/^previous$/,@{$status}) {
6346: if ($end > $now ) {
6347: return 'ok';
6348: }
6349: }
6350: if (grep/^future$/,@{$status}) {
6351: if ($start > $now) {
6352: return 'ok';
6353: }
6354: }
6355: return;
6356: }
6357:
6358: sub parse_portfolio_url {
6359: my ($url) = @_;
6360:
6361: my ($type,$udom,$unum,$group,$file_name);
6362:
1.823 albertel 6363: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6364: $type = 1;
6365: $udom = $1;
6366: $unum = $2;
6367: $file_name = $3;
1.823 albertel 6368: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6369: $type = 2;
6370: $udom = $1;
6371: $unum = $2;
6372: $group = $3;
6373: $file_name = $3.'/'.$4;
6374: }
6375: if (wantarray) {
6376: return ($type,$udom,$unum,$file_name,$group);
6377: }
6378: return $type;
6379: }
6380:
6381: sub is_portfolio_url {
6382: my ($url) = @_;
6383: return scalar(&parse_portfolio_url($url));
6384: }
6385:
1.798 raeburn 6386: sub is_portfolio_file {
6387: my ($file) = @_;
1.820 raeburn 6388: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6389: return 1;
6390: }
6391: return;
6392: }
6393:
1.976 raeburn 6394: sub usertools_access {
1.1084 raeburn 6395: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6396: my ($access,%tools);
6397: if ($context eq '') {
6398: $context = 'tools';
6399: }
6400: if ($context eq 'requestcourses') {
6401: %tools = (
6402: official => 1,
6403: unofficial => 1,
1.1006 raeburn 6404: community => 1,
1.1172.2.37 raeburn 6405: textbook => 1,
1.985 raeburn 6406: );
1.1172.2.9 raeburn 6407: } elsif ($context eq 'requestauthor') {
6408: %tools = (
6409: requestauthor => 1,
6410: );
1.985 raeburn 6411: } else {
6412: %tools = (
6413: aboutme => 1,
6414: blog => 1,
1.1172.2.6 raeburn 6415: webdav => 1,
1.985 raeburn 6416: portfolio => 1,
6417: );
6418: }
1.976 raeburn 6419: return if (!defined($tools{$tool}));
6420:
1.1172.2.35 raeburn 6421: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6422: $udom = $env{'user.domain'};
6423: $uname = $env{'user.name'};
6424: }
6425:
1.978 raeburn 6426: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6427: if ($action ne 'reload') {
1.985 raeburn 6428: if ($context eq 'requestcourses') {
6429: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6430: } elsif ($context eq 'requestauthor') {
6431: return $env{'environment.canrequest.author'};
1.985 raeburn 6432: } else {
6433: return $env{'environment.availabletools.'.$tool};
6434: }
6435: }
1.976 raeburn 6436: }
6437:
1.1172.2.9 raeburn 6438: my ($toolstatus,$inststatus,$envkey);
6439: if ($context eq 'requestauthor') {
6440: $envkey = $context;
6441: } else {
6442: $envkey = $context.'.'.$tool;
6443: }
1.976 raeburn 6444:
1.985 raeburn 6445: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6446: ($action ne 'reload')) {
1.1172.2.9 raeburn 6447: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6448: $inststatus = $env{'environment.inststatus'};
6449: } else {
1.1084 raeburn 6450: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6451: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6452: $inststatus = $userenvref->{'inststatus'};
6453: } else {
1.1172.2.9 raeburn 6454: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6455: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6456: $inststatus = $userenv{'inststatus'};
6457: }
1.976 raeburn 6458: }
6459:
6460: if ($toolstatus ne '') {
6461: if ($toolstatus) {
6462: $access = 1;
6463: } else {
6464: $access = 0;
6465: }
6466: return $access;
6467: }
6468:
1.1084 raeburn 6469: my ($is_adv,%domdef);
6470: if (ref($is_advref) eq 'HASH') {
6471: $is_adv = $is_advref->{'is_adv'};
6472: } else {
6473: $is_adv = &is_advanced_user($udom,$uname);
6474: }
6475: if (ref($domdefref) eq 'HASH') {
6476: %domdef = %{$domdefref};
6477: } else {
6478: %domdef = &get_domain_defaults($udom);
6479: }
1.976 raeburn 6480: if (ref($domdef{$tool}) eq 'HASH') {
6481: if ($is_adv) {
6482: if ($domdef{$tool}{'_LC_adv'} ne '') {
6483: if ($domdef{$tool}{'_LC_adv'}) {
6484: $access = 1;
6485: } else {
6486: $access = 0;
6487: }
6488: return $access;
6489: }
6490: }
6491: if ($inststatus ne '') {
6492: my ($hasaccess,$hasnoaccess);
6493: foreach my $affiliation (split(/:/,$inststatus)) {
6494: if ($domdef{$tool}{$affiliation} ne '') {
6495: if ($domdef{$tool}{$affiliation}) {
6496: $hasaccess = 1;
6497: } else {
6498: $hasnoaccess = 1;
6499: }
6500: }
6501: }
6502: if ($hasaccess || $hasnoaccess) {
6503: if ($hasaccess) {
6504: $access = 1;
6505: } elsif ($hasnoaccess) {
6506: $access = 0;
6507: }
6508: return $access;
6509: }
6510: } else {
6511: if ($domdef{$tool}{'default'} ne '') {
6512: if ($domdef{$tool}{'default'}) {
6513: $access = 1;
6514: } elsif ($domdef{$tool}{'default'} == 0) {
6515: $access = 0;
6516: }
6517: return $access;
6518: }
6519: }
6520: } else {
1.1172.2.6 raeburn 6521: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6522: $access = 1;
6523: } else {
6524: $access = 0;
6525: }
1.976 raeburn 6526: return $access;
6527: }
6528: }
6529:
1.1050 raeburn 6530: sub is_course_owner {
6531: my ($cdom,$cnum,$udom,$uname) = @_;
6532: if (($udom eq '') || ($uname eq '')) {
6533: $udom = $env{'user.domain'};
6534: $uname = $env{'user.name'};
6535: }
6536: unless (($udom eq '') || ($uname eq '')) {
6537: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6538: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6539: return 1;
6540: } else {
6541: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6542: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6543: return 1;
6544: }
6545: }
6546: }
6547: }
6548: return;
6549: }
6550:
1.976 raeburn 6551: sub is_advanced_user {
6552: my ($udom,$uname) = @_;
1.1085 raeburn 6553: if ($udom ne '' && $uname ne '') {
6554: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6555: if (wantarray) {
6556: return ($env{'user.adv'},$env{'user.author'});
6557: } else {
6558: return $env{'user.adv'};
6559: }
1.1085 raeburn 6560: }
6561: }
1.976 raeburn 6562: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6563: my %allroles;
1.1128 raeburn 6564: my ($is_adv,$is_author);
1.976 raeburn 6565: foreach my $role (keys(%roleshash)) {
6566: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6567: my $area = '/'.$tdomain.'/'.$trest;
6568: if ($sec ne '') {
6569: $area .= '/'.$sec;
6570: }
6571: if (($area ne '') && ($trole ne '')) {
6572: my $spec=$trole.'.'.$area;
6573: if ($trole =~ /^cr\//) {
6574: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6575: } elsif ($trole ne 'gr') {
6576: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6577: }
1.1128 raeburn 6578: if ($trole eq 'au') {
6579: $is_author = 1;
6580: }
1.976 raeburn 6581: }
6582: }
6583: foreach my $role (keys(%allroles)) {
6584: last if ($is_adv);
6585: foreach my $item (split(/:/,$allroles{$role})) {
6586: if ($item ne '') {
6587: my ($privilege,$restrictions)=split(/&/,$item);
6588: if ($privilege eq 'adv') {
6589: $is_adv = 1;
6590: last;
6591: }
6592: }
6593: }
6594: }
1.1128 raeburn 6595: if (wantarray) {
6596: return ($is_adv,$is_author);
6597: }
1.976 raeburn 6598: return $is_adv;
6599: }
1.798 raeburn 6600:
1.1035 raeburn 6601: sub check_can_request {
1.1036 raeburn 6602: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6603: my $canreq = 0;
6604: my ($types,$typename) = &Apache::loncommon::course_types();
6605: my @options = ('approval','validate','autolimit');
6606: my $optregex = join('|',@options);
6607: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6608: foreach my $type (@{$types}) {
6609: if (&usertools_access($env{'user.name'},
6610: $env{'user.domain'},
6611: $type,undef,'requestcourses')) {
6612: $canreq ++;
1.1036 raeburn 6613: if (ref($request_domains) eq 'HASH') {
6614: push(@{$request_domains->{$type}},$env{'user.domain'});
6615: }
1.1035 raeburn 6616: if ($dom eq $env{'user.domain'}) {
6617: $can_request->{$type} = 1;
6618: }
6619: }
6620: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6621: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6622: if (@curr > 0) {
1.1036 raeburn 6623: foreach my $item (@curr) {
6624: if (ref($request_domains) eq 'HASH') {
6625: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6626: if ($otherdom ne '') {
6627: if (ref($request_domains->{$type}) eq 'ARRAY') {
6628: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6629: push(@{$request_domains->{$type}},$otherdom);
6630: }
6631: } else {
6632: push(@{$request_domains->{$type}},$otherdom);
6633: }
6634: }
6635: }
6636: }
6637: unless($dom eq $env{'user.domain'}) {
6638: $canreq ++;
1.1035 raeburn 6639: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6640: $can_request->{$type} = 1;
6641: }
6642: }
6643: }
6644: }
6645: }
6646: }
6647: return $canreq;
6648: }
6649:
1.341 www 6650: # ---------------------------------------------- Custom access rule evaluation
6651:
6652: sub customaccess {
6653: my ($priv,$uri)=@_;
1.807 albertel 6654: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6655: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6656: $udom = &LONCAPA::clean_domain($udom);
6657: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6658: my $access=0;
1.800 albertel 6659: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6660: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6661: if ($type eq 'user') {
6662: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6663: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6664: if ($tdom) {
6665: if ($tdom ne $env{'user.domain'}) { next; }
6666: }
1.896 albertel 6667: if ($tuname) {
6668: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6669: }
6670: $access=($effect eq 'allow');
6671: last;
6672: }
6673: } else {
6674: if ($role) {
6675: if ($role ne $urole) { next; }
6676: }
6677: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6678: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6679: if ($tdom) {
6680: if ($tdom ne $udom) { next; }
6681: }
6682: if ($tcrs) {
6683: if ($tcrs ne $ucrs) { next; }
6684: }
6685: if ($tsec) {
6686: if ($tsec ne $usec) { next; }
6687: }
6688: $access=($effect eq 'allow');
6689: last;
6690: }
6691: if ($realm eq '' && $role eq '') {
6692: $access=($effect eq 'allow');
6693: }
1.402 bowersj2 6694: }
1.341 www 6695: }
6696: return $access;
6697: }
6698:
1.103 harris41 6699: # ------------------------------------------------- Check for a user privilege
1.12 www 6700:
6701: sub allowed {
1.810 raeburn 6702: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6703: my $ver_orguri=$uri;
1.439 www 6704: $uri=&deversion($uri);
1.152 www 6705: my $orguri=$uri;
1.52 www 6706: $uri=&declutter($uri);
1.809 raeburn 6707:
1.810 raeburn 6708: if ($priv eq 'evb') {
6709: # Evade communication block restrictions for specified role in a course
6710: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6711: return $1;
6712: } else {
6713: return;
6714: }
6715: }
6716:
1.620 albertel 6717: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6718: # Free bre access to adm and meta resources
1.775 albertel 6719: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6720: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6721: && ($priv eq 'bre')) {
1.14 www 6722: return 'F';
1.159 www 6723: }
6724:
1.545 banghart 6725: # Free bre access to user's own portfolio contents
1.714 raeburn 6726: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6727: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6728: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6729: my %setters;
6730: my ($startblock,$endblock) =
6731: &Apache::loncommon::blockcheck(\%setters,'port');
6732: if ($startblock && $endblock) {
6733: return 'B';
6734: } else {
6735: return 'F';
6736: }
1.545 banghart 6737: }
6738:
1.762 raeburn 6739: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6740: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6741: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6742: if (exists($env{'request.course.id'})) {
6743: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6744: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6745: if (($domain eq $cdom) && ($name eq $cnum)) {
6746: my $courseprivid=$env{'request.course.id'};
6747: $courseprivid=~s/\_/\//;
6748: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6749: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6750: return $1;
1.762 raeburn 6751: } else {
6752: if ($env{'request.course.sec'}) {
6753: $courseprivid.='/'.$env{'request.course.sec'};
6754: }
6755: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6756: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6757: return $2;
6758: }
1.714 raeburn 6759: }
6760: }
6761: }
6762: }
6763:
1.159 www 6764: # Free bre to public access
6765:
6766: if ($priv eq 'bre') {
1.238 www 6767: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6768: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6769: return 'F';
6770: }
1.238 www 6771: if ($copyright eq 'priv') {
6772: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6773: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6774: return '';
6775: }
6776: }
6777: if ($copyright eq 'domain') {
6778: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6779: unless (($env{'user.domain'} eq $1) ||
6780: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6781: return '';
6782: }
1.262 matthew 6783: }
1.620 albertel 6784: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6785: # Library role, so allow browsing of resources in this domain.
6786: return 'F';
1.238 www 6787: }
1.341 www 6788: if ($copyright eq 'custom') {
6789: unless (&customaccess($priv,$uri)) { return ''; }
6790: }
1.14 www 6791: }
1.264 matthew 6792: # Domain coordinator is trying to create a course
1.620 albertel 6793: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6794: # uri is the requested domain in this case.
6795: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6796: # a role of dc for the domain in question.
1.620 albertel 6797: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6798: }
1.29 www 6799:
1.52 www 6800: my $thisallowed='';
6801: my $statecond=0;
6802: my $courseprivid='';
6803:
1.1039 raeburn 6804: my $ownaccess;
1.1043 raeburn 6805: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6806: if (($priv eq 'bro') && ($env{'user.author'})) {
6807: if ($uri eq '') {
6808: $ownaccess = 1;
6809: } else {
6810: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6811: my $udom = $env{'user.domain'};
6812: my $uname = $env{'user.name'};
6813: if ($uri =~ m{^\Q$udom\E/?$}) {
6814: $ownaccess = 1;
1.1040 raeburn 6815: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6816: unless ($uri =~ m{\.\./}) {
6817: $ownaccess = 1;
6818: }
6819: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6820: my $now = time;
6821: if ($uri =~ m{^([^/]+)/?$}) {
6822: my $adom = $1;
6823: foreach my $key (keys(%env)) {
1.1042 raeburn 6824: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6825: my ($start,$end) = split('.',$env{$key});
6826: if (($now >= $start) && (!$end || $end < $now)) {
6827: $ownaccess = 1;
6828: last;
6829: }
6830: }
6831: }
6832: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6833: my $adom = $1;
6834: my $aname = $2;
1.1042 raeburn 6835: foreach my $role ('ca','aa') {
6836: if ($env{"user.role.$role./$adom/$aname"}) {
6837: my ($start,$end) =
6838: split('.',$env{"user.role.$role./$adom/$aname"});
6839: if (($now >= $start) && (!$end || $end < $now)) {
6840: $ownaccess = 1;
6841: last;
6842: }
1.1039 raeburn 6843: }
6844: }
6845: }
6846: }
6847: }
6848: }
6849: }
6850:
1.52 www 6851: # Course
6852:
1.620 albertel 6853: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6854: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6855: $thisallowed.=$1;
6856: }
1.52 www 6857: }
1.29 www 6858:
1.52 www 6859: # Domain
6860:
1.620 albertel 6861: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6862: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6863: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6864: $thisallowed.=$1;
6865: }
1.12 www 6866: }
1.52 www 6867:
1.1141 raeburn 6868: # User who is not author or co-author might still be able to edit
6869: # resource of an author in the domain (e.g., if Domain Coordinator).
6870: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6871: (&allowed('mdc',$env{'request.course.id'}))) {
6872: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6873: $thisallowed.=$1;
6874: }
6875: }
6876:
1.52 www 6877: # Course: uri itself is a course
1.66 www 6878: my $courseuri=$uri;
6879: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6880: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6881:
1.620 albertel 6882: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6883: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6884: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6885: $thisallowed.=$1;
6886: }
1.12 www 6887: }
1.29 www 6888:
1.665 albertel 6889: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6890: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6891: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6892: $thisallowed='';
1.671 raeburn 6893: my ($match)=&is_on_map($uri);
6894: if ($match) {
6895: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6896: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6897: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6898: if (@blockers > 0) {
6899: $thisallowed = 'B';
6900: } else {
6901: $thisallowed.=$1;
6902: }
1.671 raeburn 6903: }
6904: } else {
1.705 albertel 6905: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6906: if ($refuri) {
6907: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6908: $thisallowed='F';
1.671 raeburn 6909: } else {
6910: $refuri=&declutter($refuri);
6911: my ($match) = &is_on_map($refuri);
6912: if ($match) {
1.1162 raeburn 6913: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6914: if (@blockers > 0) {
6915: $thisallowed = 'B';
6916: } else {
6917: $thisallowed='F';
6918: }
1.671 raeburn 6919: }
1.669 raeburn 6920: }
1.671 raeburn 6921: }
6922: }
1.314 www 6923: }
1.492 albertel 6924:
1.766 albertel 6925: if ($priv eq 'bre'
6926: && $thisallowed ne 'F'
6927: && $thisallowed ne '2'
6928: && &is_portfolio_url($uri)) {
6929: $thisallowed = &portfolio_access($uri);
6930: }
6931:
1.52 www 6932: # Full access at system, domain or course-wide level? Exit.
1.29 www 6933: if ($thisallowed=~/F/) {
6934: return 'F';
6935: }
6936:
1.52 www 6937: # If this is generating or modifying users, exit with special codes
1.29 www 6938:
1.643 www 6939: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6940: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6941: my ($audom,$auname)=split('/',$uri);
1.643 www 6942: # no author name given, so this just checks on the general right to make a co-author in this domain
6943: unless ($auname) { return $thisallowed; }
6944: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6945: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6946: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6947: ($audom ne $env{'request.role.domain'}))) { return ''; }
6948: }
1.52 www 6949: return $thisallowed;
6950: }
6951: #
1.103 harris41 6952: # Gathered so far: system, domain and course wide privileges
1.52 www 6953: #
6954: # Course: See if uri or referer is an individual resource that is part of
6955: # the course
6956:
1.620 albertel 6957: if ($env{'request.course.id'}) {
1.232 www 6958:
1.620 albertel 6959: $courseprivid=$env{'request.course.id'};
6960: if ($env{'request.course.sec'}) {
6961: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6962: }
6963: $courseprivid=~s/\_/\//;
6964: my $checkreferer=1;
1.232 www 6965: my ($match,$cond)=&is_on_map($uri);
6966: if ($match) {
6967: $statecond=$cond;
1.620 albertel 6968: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6969: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6970: my $value = $1;
6971: if ($priv eq 'bre') {
6972: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6973: if (@blockers > 0) {
6974: $thisallowed = 'B';
6975: } else {
6976: $thisallowed.=$value;
6977: }
6978: } else {
6979: $thisallowed.=$value;
6980: }
1.52 www 6981: $checkreferer=0;
6982: }
1.29 www 6983: }
1.83 www 6984:
1.148 www 6985: if ($checkreferer) {
1.620 albertel 6986: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6987: unless ($refuri) {
1.800 albertel 6988: foreach my $key (keys(%env)) {
6989: if ($key=~/^httpref\..*\*/) {
6990: my $pattern=$key;
1.156 www 6991: $pattern=~s/^httpref\.\/res\///;
1.148 www 6992: $pattern=~s/\*/\[\^\/\]\+/g;
6993: $pattern=~s/\//\\\//g;
1.152 www 6994: if ($orguri=~/$pattern/) {
1.800 albertel 6995: $refuri=$env{$key};
1.148 www 6996: }
6997: }
1.191 harris41 6998: }
1.148 www 6999: }
1.232 www 7000:
1.148 www 7001: if ($refuri) {
1.152 www 7002: $refuri=&declutter($refuri);
1.232 www 7003: my ($match,$cond)=&is_on_map($refuri);
7004: if ($match) {
7005: my $refstatecond=$cond;
1.620 albertel 7006: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7007: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7008: my $value = $1;
7009: if ($priv eq 'bre') {
7010: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7011: if (@blockers > 0) {
7012: $thisallowed = 'B';
7013: } else {
7014: $thisallowed.=$value;
7015: }
7016: } else {
7017: $thisallowed.=$value;
7018: }
1.53 www 7019: $uri=$refuri;
7020: $statecond=$refstatecond;
1.52 www 7021: }
7022: }
1.148 www 7023: }
1.29 www 7024: }
1.52 www 7025: }
1.29 www 7026:
1.52 www 7027: #
1.103 harris41 7028: # Gathered now: all privileges that could apply, and condition number
1.52 www 7029: #
7030: #
7031: # Full or no access?
7032: #
1.29 www 7033:
1.52 www 7034: if ($thisallowed=~/F/) {
7035: return 'F';
7036: }
1.29 www 7037:
1.52 www 7038: unless ($thisallowed) {
7039: return '';
7040: }
1.29 www 7041:
1.52 www 7042: # Restrictions exist, deal with them
7043: #
7044: # C:according to course preferences
7045: # R:according to resource settings
7046: # L:unless locked
7047: # X:according to user session state
7048: #
7049:
7050: # Possibly locked functionality, check all courses
1.54 www 7051: # Locks might take effect only after 10 minutes cache expiration for other
7052: # courses, and 2 minutes for current course
1.52 www 7053:
7054: my $envkey;
7055: if ($thisallowed=~/L/) {
1.1000 raeburn 7056: foreach $envkey (keys(%env)) {
1.54 www 7057: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7058: my $courseid=$2;
7059: my $roleid=$1.'.'.$2;
1.92 www 7060: $courseid=~s/^\///;
1.54 www 7061: my $expiretime=600;
1.620 albertel 7062: if ($env{'request.role'} eq $roleid) {
1.54 www 7063: $expiretime=120;
7064: }
7065: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7066: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7067: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7068: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7069: }
1.620 albertel 7070: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7071: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7072: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7073: &log($env{'user.domain'},$env{'user.name'},
7074: $env{'user.home'},
1.57 www 7075: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7076: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7077: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7078: return '';
7079: }
7080: }
1.620 albertel 7081: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7082: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7083: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7084: &log($env{'user.domain'},$env{'user.name'},
7085: $env{'user.home'},
1.57 www 7086: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7087: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7088: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7089: return '';
7090: }
7091: }
7092: }
1.29 www 7093: }
1.52 www 7094: }
7095:
7096: #
7097: # Rest of the restrictions depend on selected course
7098: #
7099:
1.620 albertel 7100: unless ($env{'request.course.id'}) {
1.766 albertel 7101: if ($thisallowed eq 'A') {
7102: return 'A';
1.814 raeburn 7103: } elsif ($thisallowed eq 'B') {
7104: return 'B';
1.766 albertel 7105: } else {
7106: return '1';
7107: }
1.52 www 7108: }
1.29 www 7109:
1.52 www 7110: #
7111: # Now user is definitely in a course
7112: #
1.53 www 7113:
7114:
7115: # Course preferences
7116:
7117: if ($thisallowed=~/C/) {
1.620 albertel 7118: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7119: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7120: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7121: =~/\Q$rolecode\E/) {
1.1103 raeburn 7122: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7123: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7124: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7125: $env{'request.course.id'});
7126: }
1.237 www 7127: return '';
7128: }
7129:
1.620 albertel 7130: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7131: =~/\Q$unamedom\E/) {
1.1103 raeburn 7132: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7133: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7134: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7135: $env{'request.course.id'});
7136: }
1.54 www 7137: return '';
7138: }
1.53 www 7139: }
7140:
7141: # Resource preferences
7142:
7143: if ($thisallowed=~/R/) {
1.620 albertel 7144: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7145: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7146: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7147: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7148: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7149: }
7150: return '';
1.54 www 7151: }
1.53 www 7152: }
1.30 www 7153:
1.246 www 7154: # Restricted by state or randomout?
1.30 www 7155:
1.52 www 7156: if ($thisallowed=~/X/) {
1.620 albertel 7157: if ($env{'acc.randomout'}) {
1.579 albertel 7158: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7159: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7160: return '';
7161: }
1.247 www 7162: }
7163: if (&condval($statecond)) {
1.52 www 7164: return '2';
7165: } else {
7166: return '';
7167: }
7168: }
1.30 www 7169:
1.766 albertel 7170: if ($thisallowed eq 'A') {
7171: return 'A';
1.814 raeburn 7172: } elsif ($thisallowed eq 'B') {
7173: return 'B';
1.766 albertel 7174: }
1.52 www 7175: return 'F';
1.232 www 7176: }
1.1162 raeburn 7177:
1.1172.2.13 raeburn 7178: # ------------------------------------------- Check construction space access
7179:
7180: sub constructaccess {
7181: my ($url,$setpriv)=@_;
7182:
7183: # We do not allow editing of previous versions of files
7184: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7185:
7186: # Get username and domain from URL
7187: my ($ownername,$ownerdomain,$ownerhome);
7188:
7189: ($ownerdomain,$ownername) =
7190: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7191:
7192: # The URL does not really point to any authorspace, forget it
7193: unless (($ownername) && ($ownerdomain)) { return ''; }
7194:
7195: # Now we need to see if the user has access to the authorspace of
7196: # $ownername at $ownerdomain
7197:
7198: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7199: # Real author for this?
7200: $ownerhome = $env{'user.home'};
7201: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7202: return ($ownername,$ownerdomain,$ownerhome);
7203: }
7204: } else {
7205: # Co-author for this?
7206: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7207: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7208: $ownerhome = &homeserver($ownername,$ownerdomain);
7209: return ($ownername,$ownerdomain,$ownerhome);
7210: }
7211: }
7212:
7213: # We don't have any access right now. If we are not possibly going to do anything about this,
7214: # we might as well leave
7215: unless ($setpriv) { return ''; }
7216:
7217: # Backdoor access?
7218: my $allowed=&allowed('eco',$ownerdomain);
7219: # Nope
7220: unless ($allowed) { return ''; }
7221: # Looks like we may have access, but could be locked by the owner of the construction space
7222: if ($allowed eq 'U') {
7223: my %blocked=&get('environment',['domcoord.author'],
7224: $ownerdomain,$ownername);
7225: # Is blocked by owner
7226: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7227: }
7228: if (($allowed eq 'F') || ($allowed eq 'U')) {
7229: # Grant temporary access
7230: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7231: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7232: if (!$update) { $update = $then; }
7233: my $refresh=$env{'user.refresh.time'};
7234: if (!$refresh) { $refresh = $update; }
7235: my $now = time;
7236: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7237: $now,'ca','constructaccess');
7238: $ownerhome = &homeserver($ownername,$ownerdomain);
7239: return($ownername,$ownerdomain,$ownerhome);
7240: }
7241: # No business here
7242: return '';
7243: }
7244:
1.1162 raeburn 7245: sub get_comm_blocks {
7246: my ($cdom,$cnum) = @_;
7247: if ($cdom eq '' || $cnum eq '') {
7248: return unless ($env{'request.course.id'});
7249: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7250: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7251: }
7252: my %commblocks;
7253: my $hashid=$cdom.'_'.$cnum;
7254: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7255: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7256: %commblocks = %{$blocksref};
7257: } else {
7258: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7259: my $cachetime = 600;
7260: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7261: }
7262: return %commblocks;
7263: }
7264:
7265: sub has_comm_blocking {
7266: my ($priv,$symb,$uri,$blocks) = @_;
7267: return unless ($env{'request.course.id'});
7268: return unless ($priv eq 'bre');
7269: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7270: my %commblocks;
7271: if (ref($blocks) eq 'HASH') {
7272: %commblocks = %{$blocks};
7273: } else {
7274: %commblocks = &get_comm_blocks();
7275: }
7276: return unless (keys(%commblocks) > 0);
7277: if (!$symb) { $symb=&symbread($uri,1); }
7278: my ($map,$resid,undef)=&decode_symb($symb);
7279: my %tocheck = (
7280: maps => $map,
7281: resources => $symb,
7282: );
7283: my @blockers;
7284: my $now = time;
1.1163 raeburn 7285: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7286: foreach my $block (keys(%commblocks)) {
7287: if ($block =~ /^(\d+)____(\d+)$/) {
7288: my ($start,$end) = ($1,$2);
7289: if ($start <= $now && $end >= $now) {
7290: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7291: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7292: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7293: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7294: unless (grep(/^\Q$block\E$/,@blockers)) {
7295: push(@blockers,$block);
7296: }
7297: }
7298: }
7299: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7300: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7301: unless (grep(/^\Q$block\E$/,@blockers)) {
7302: push(@blockers,$block);
7303: }
7304: }
7305: }
7306: }
7307: }
7308: }
7309: } elsif ($block =~ /^firstaccess____(.+)$/) {
7310: my $item = $1;
1.1163 raeburn 7311: my @to_test;
1.1162 raeburn 7312: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7313: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7314: my $check_interval;
7315: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7316: my @interval;
7317: my $type = 'map';
7318: if ($item eq 'course') {
7319: $type = 'course';
7320: @interval=&EXT("resource.0.interval");
7321: } else {
7322: if ($item =~ /___\d+___/) {
7323: $type = 'resource';
7324: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7325: if (ref($navmap)) {
7326: my $res = $navmap->getBySymb($item);
7327: push(@to_test,$res);
7328: }
1.1162 raeburn 7329: } else {
7330: my $mapsymb = &symbread($item,1);
7331: if ($mapsymb) {
7332: if (ref($navmap)) {
7333: my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.63! raeburn 7334: @to_test = $mapres->retrieveResources($mapres);
1.1163 raeburn 7335: foreach my $res (@to_test) {
1.1162 raeburn 7336: my $symb = $res->symb();
7337: next if ($symb eq $mapsymb);
7338: if ($symb ne '') {
7339: @interval=&EXT("resource.0.interval",$symb);
1.1172.2.63! raeburn 7340: if ($interval[1] eq 'map') {
! 7341: last;
! 7342: }
1.1162 raeburn 7343: }
7344: }
7345: }
7346: }
7347: }
7348: }
7349: if ($interval[0] =~ /\d+/) {
7350: my $first_access;
7351: if ($type eq 'resource') {
7352: $first_access=&get_first_access($interval[1],$item);
7353: } elsif ($type eq 'map') {
7354: $first_access=&get_first_access($interval[1],undef,$item);
7355: } else {
7356: $first_access=&get_first_access($interval[1]);
7357: }
7358: if ($first_access) {
7359: my $timesup = $first_access+$interval[0];
7360: if ($timesup > $now) {
1.1163 raeburn 7361: foreach my $res (@to_test) {
7362: if ($res->is_problem()) {
7363: if ($res->completable()) {
7364: unless (grep(/^\Q$block\E$/,@blockers)) {
7365: push(@blockers,$block);
7366: }
7367: last;
7368: }
7369: }
1.1162 raeburn 7370: }
7371: }
7372: }
7373: }
7374: }
7375: }
7376: }
7377: }
7378: }
7379: return @blockers;
7380: }
7381:
7382: sub check_docs_block {
7383: my ($docsblock,$tocheck) =@_;
7384: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7385: return;
7386: }
7387: if (ref($docsblock->{'maps'}) eq 'HASH') {
7388: if ($tocheck->{'maps'}) {
7389: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7390: return 1;
7391: }
7392: }
7393: }
7394: if (ref($docsblock->{'resources'}) eq 'HASH') {
7395: if ($tocheck->{'resources'}) {
7396: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7397: return 1;
7398: }
7399: }
7400: }
7401: return;
7402: }
7403:
1.1133 foxr 7404: #
7405: # Removes the versino from a URI and
7406: # splits it in to its filename and path to the filename.
7407: # Seems like File::Basename could have done this more clearly.
7408: # Parameters:
7409: # $uri - input URI
7410: # Returns:
7411: # Two element list consisting of
7412: # $pathname - the URI up to and excluding the trailing /
7413: # $filename - The part of the URI following the last /
7414: # NOTE:
7415: # Another realization of this is simply:
7416: # use File::Basename;
7417: # ...
7418: # $uri = shift;
7419: # $filename = basename($uri);
7420: # $path = dirname($uri);
7421: # return ($filename, $path);
7422: #
7423: # The implementation below is probably faster however.
7424: #
1.710 albertel 7425: sub split_uri_for_cond {
7426: my $uri=&deversion(&declutter(shift));
7427: my @uriparts=split(/\//,$uri);
7428: my $filename=pop(@uriparts);
7429: my $pathname=join('/',@uriparts);
7430: return ($pathname,$filename);
7431: }
1.232 www 7432: # --------------------------------------------------- Is a resource on the map?
7433:
7434: sub is_on_map {
1.710 albertel 7435: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7436: #Trying to find the conditional for the file
1.620 albertel 7437: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7438: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7439: if ($match) {
1.289 bowersj2 7440: return (1,$1);
7441: } else {
1.434 www 7442: return (0,0);
1.289 bowersj2 7443: }
1.12 www 7444: }
7445:
1.427 www 7446: # --------------------------------------------------------- Get symb from alias
7447:
7448: sub get_symb_from_alias {
7449: my $symb=shift;
7450: my ($map,$resid,$url)=&decode_symb($symb);
7451: # Already is a symb
7452: if ($url) { return $symb; }
7453: # Must be an alias
7454: my $aliassymb='';
7455: my %bighash;
1.620 albertel 7456: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7457: &GDBM_READER(),0640)) {
7458: my $rid=$bighash{'mapalias_'.$symb};
7459: if ($rid) {
7460: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7461: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7462: $resid,$bighash{'src_'.$rid});
1.427 www 7463: }
7464: untie %bighash;
7465: }
7466: return $aliassymb;
7467: }
7468:
1.12 www 7469: # ----------------------------------------------------------------- Define Role
7470:
7471: sub definerole {
7472: if (allowed('mcr','/')) {
7473: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7474: foreach my $role (split(':',$sysrole)) {
7475: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7476: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7477: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7478: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7479: return "refused:s:$crole&$cqual";
7480: }
7481: }
1.191 harris41 7482: }
1.800 albertel 7483: foreach my $role (split(':',$domrole)) {
7484: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7485: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7486: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7487: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7488: return "refused:d:$crole&$cqual";
7489: }
7490: }
1.191 harris41 7491: }
1.800 albertel 7492: foreach my $role (split(':',$courole)) {
7493: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7494: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7495: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7496: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7497: return "refused:c:$crole&$cqual";
7498: }
7499: }
1.191 harris41 7500: }
1.620 albertel 7501: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7502: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7503: "rolesdef_$rolename=".
7504: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7505: return reply($command,$env{'user.home'});
1.12 www 7506: } else {
7507: return 'refused';
7508: }
1.105 harris41 7509: }
7510:
7511: # ---------------- Make a metadata query against the network of library servers
7512:
7513: sub metadata_query {
1.1172.2.33 raeburn 7514: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7515: my %rhash;
1.845 albertel 7516: my %libserv = &all_library();
1.244 matthew 7517: my @server_list = (defined($server_array) ? @$server_array
7518: : keys(%libserv) );
7519: for my $server (@server_list) {
1.1172.2.33 raeburn 7520: my $domains = '';
7521: if (ref($domains_hash) eq 'HASH') {
7522: $domains = $domains_hash->{$server};
7523: }
1.118 harris41 7524: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7525: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7526: $rhash{$server}=$reply;
7527: }
7528: else {
7529: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7530: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7531: $server);
7532: $rhash{$server}=$reply;
7533: }
1.112 harris41 7534: }
1.118 harris41 7535: return \%rhash;
1.240 www 7536: }
7537:
7538: # ----------------------------------------- Send log queries and wait for reply
7539:
7540: sub log_query {
7541: my ($uname,$udom,$query,%filters)=@_;
7542: my $uhome=&homeserver($uname,$udom);
7543: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7544: my $uhost=&hostname($uhome);
1.800 albertel 7545: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7546: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7547: $uhome);
1.479 albertel 7548: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7549: return get_query_reply($queryid);
7550: }
7551:
1.818 raeburn 7552: # -------------------------- Update MySQL table for portfolio file
7553:
7554: sub update_portfolio_table {
1.821 raeburn 7555: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7556: if ($group ne '') {
7557: $file_name =~s /^\Q$group\E//;
7558: }
1.818 raeburn 7559: my $homeserver = &homeserver($uname,$udom);
7560: my $queryid=
1.821 raeburn 7561: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7562: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7563: my $reply = &get_query_reply($queryid);
7564: return $reply;
7565: }
7566:
1.899 raeburn 7567: # -------------------------- Update MySQL allusers table
7568:
7569: sub update_allusers_table {
7570: my ($uname,$udom,$names) = @_;
7571: my $homeserver = &homeserver($uname,$udom);
7572: my $queryid=
7573: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7574: 'lastname='.&escape($names->{'lastname'}).'%%'.
7575: 'firstname='.&escape($names->{'firstname'}).'%%'.
7576: 'middlename='.&escape($names->{'middlename'}).'%%'.
7577: 'generation='.&escape($names->{'generation'}).'%%'.
7578: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7579: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7580: return;
1.899 raeburn 7581: }
7582:
1.508 raeburn 7583: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7584:
7585: sub fetch_enrollment_query {
1.511 raeburn 7586: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7587: my $homeserver;
1.547 raeburn 7588: my $maxtries = 1;
1.508 raeburn 7589: if ($context eq 'automated') {
7590: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7591: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7592: } else {
7593: $homeserver = &homeserver($cnum,$dom);
7594: }
1.838 albertel 7595: my $host=&hostname($homeserver);
1.506 raeburn 7596: my $cmd = '';
1.1000 raeburn 7597: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7598: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7599: }
7600: $cmd =~ s/%%$//;
7601: $cmd = &escape($cmd);
7602: my $query = 'fetchenrollment';
1.620 albertel 7603: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7604: unless ($queryid=~/^\Q$host\E\_/) {
7605: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7606: return 'error: '.$queryid;
7607: }
1.506 raeburn 7608: my $reply = &get_query_reply($queryid);
1.547 raeburn 7609: my $tries = 1;
7610: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7611: $reply = &get_query_reply($queryid);
7612: $tries ++;
7613: }
1.526 raeburn 7614: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7615: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7616: } else {
1.901 albertel 7617: my @responses = split(/:/,$reply);
1.515 raeburn 7618: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7619: foreach my $line (@responses) {
7620: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7621: $$replyref{$key} = $value;
7622: }
7623: } else {
1.1117 foxr 7624: my $pathname = LONCAPA::tempdir();
1.800 albertel 7625: foreach my $line (@responses) {
7626: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7627: $$replyref{$key} = $value;
7628: if ($value > 0) {
1.800 albertel 7629: foreach my $item (@{$$affiliatesref{$key}}) {
7630: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7631: my $destname = $pathname.'/'.$filename;
7632: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7633: if ($xml_classlist =~ /^error/) {
7634: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7635: } else {
1.506 raeburn 7636: if ( open(FILE,">$destname") ) {
7637: print FILE &unescape($xml_classlist);
7638: close(FILE);
1.526 raeburn 7639: } else {
7640: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7641: }
7642: }
7643: }
7644: }
7645: }
7646: }
7647: return 'ok';
7648: }
7649: return 'error';
7650: }
7651:
1.242 www 7652: sub get_query_reply {
7653: my $queryid=shift;
1.1117 foxr 7654: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7655: my $reply='';
7656: for (1..100) {
7657: sleep 2;
7658: if (-e $replyfile.'.end') {
1.448 albertel 7659: if (open(my $fh,$replyfile)) {
1.904 albertel 7660: $reply = join('',<$fh>);
7661: close($fh);
1.240 www 7662: } else { return 'error: reply_file_error'; }
1.242 www 7663: return &unescape($reply);
7664: }
1.240 www 7665: }
1.242 www 7666: return 'timeout:'.$queryid;
1.240 www 7667: }
7668:
7669: sub courselog_query {
1.241 www 7670: #
7671: # possible filters:
7672: # url: url or symb
7673: # username
7674: # domain
7675: # action: view, submit, grade
7676: # start: timestamp
7677: # end: timestamp
7678: #
1.240 www 7679: my (%filters)=@_;
1.620 albertel 7680: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7681: if ($filters{'url'}) {
7682: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7683: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7684: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7685: }
1.620 albertel 7686: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7687: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7688: return &log_query($cname,$cdom,'courselog',%filters);
7689: }
7690:
7691: sub userlog_query {
1.858 raeburn 7692: #
7693: # possible filters:
7694: # action: log check role
7695: # start: timestamp
7696: # end: timestamp
7697: #
1.240 www 7698: my ($uname,$udom,%filters)=@_;
7699: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7700: }
7701:
1.506 raeburn 7702: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7703:
7704: sub auto_run {
1.508 raeburn 7705: my ($cnum,$cdom) = @_;
1.876 raeburn 7706: my $response = 0;
7707: my $settings;
7708: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7709: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7710: $settings = $domconfig{'autoenroll'};
7711: if ($settings->{'run'} eq '1') {
7712: $response = 1;
7713: }
7714: } else {
1.934 raeburn 7715: my $homeserver;
7716: if (&is_course($cdom,$cnum)) {
7717: $homeserver = &homeserver($cnum,$cdom);
7718: } else {
7719: $homeserver = &domain($cdom,'primary');
7720: }
7721: if ($homeserver ne 'no_host') {
7722: $response = &reply('autorun:'.$cdom,$homeserver);
7723: }
1.876 raeburn 7724: }
1.506 raeburn 7725: return $response;
7726: }
1.776 albertel 7727:
1.506 raeburn 7728: sub auto_get_sections {
1.508 raeburn 7729: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7730: my $homeserver;
7731: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7732: $homeserver = &homeserver($cnum,$cdom);
7733: }
7734: if (!defined($homeserver)) {
7735: if ($cdom =~ /^$match_domain$/) {
7736: $homeserver = &domain($cdom,'primary');
7737: }
7738: }
7739: my @secs;
7740: if (defined($homeserver)) {
7741: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7742: unless ($response eq 'refused') {
7743: @secs = split(/:/,$response);
7744: }
1.506 raeburn 7745: }
7746: return @secs;
7747: }
1.776 albertel 7748:
1.506 raeburn 7749: sub auto_new_course {
1.1099 raeburn 7750: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7751: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7752: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7753: return $response;
7754: }
1.776 albertel 7755:
1.506 raeburn 7756: sub auto_validate_courseID {
1.508 raeburn 7757: my ($cnum,$cdom,$inst_course_id) = @_;
7758: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7759: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7760: return $response;
7761: }
1.776 albertel 7762:
1.1007 raeburn 7763: sub auto_validate_instcode {
1.1020 raeburn 7764: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7765: my ($homeserver,$response);
7766: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7767: $homeserver = &homeserver($cnum,$cdom);
7768: }
7769: if (!defined($homeserver)) {
7770: if ($cdom =~ /^$match_domain$/) {
7771: $homeserver = &domain($cdom,'primary');
7772: }
7773: }
1.1065 raeburn 7774: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7775: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7776: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7777: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7778: }
7779:
1.506 raeburn 7780: sub auto_create_password {
1.873 raeburn 7781: my ($cnum,$cdom,$authparam,$udom) = @_;
7782: my ($homeserver,$response);
1.506 raeburn 7783: my $create_passwd = 0;
7784: my $authchk = '';
1.873 raeburn 7785: if ($udom =~ /^$match_domain$/) {
7786: $homeserver = &domain($udom,'primary');
7787: }
7788: if ($homeserver eq '') {
7789: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7790: $homeserver = &homeserver($cnum,$cdom);
7791: }
7792: }
7793: if ($homeserver eq '') {
7794: $authchk = 'nodomain';
1.506 raeburn 7795: } else {
1.873 raeburn 7796: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7797: if ($response eq 'refused') {
7798: $authchk = 'refused';
7799: } else {
1.901 albertel 7800: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7801: }
1.506 raeburn 7802: }
7803: return ($authparam,$create_passwd,$authchk);
7804: }
7805:
1.706 raeburn 7806: sub auto_photo_permission {
7807: my ($cnum,$cdom,$students) = @_;
7808: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7809: my ($outcome,$perm_reqd,$conditions) =
7810: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7811: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7812: return (undef,undef);
7813: }
1.706 raeburn 7814: return ($outcome,$perm_reqd,$conditions);
7815: }
7816:
7817: sub auto_checkphotos {
7818: my ($uname,$udom,$pid) = @_;
7819: my $homeserver = &homeserver($uname,$udom);
7820: my ($result,$resulttype);
7821: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7822: &escape($uname).':'.&escape($pid),
7823: $homeserver));
1.709 albertel 7824: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7825: return (undef,undef);
7826: }
1.706 raeburn 7827: if ($outcome) {
7828: ($result,$resulttype) = split(/:/,$outcome);
7829: }
7830: return ($result,$resulttype);
7831: }
7832:
7833: sub auto_photochoice {
7834: my ($cnum,$cdom) = @_;
7835: my $homeserver = &homeserver($cnum,$cdom);
7836: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7837: &escape($cdom),
7838: $homeserver)));
1.709 albertel 7839: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7840: return (undef,undef);
7841: }
1.706 raeburn 7842: return ($update,$comment);
7843: }
7844:
7845: sub auto_photoupdate {
7846: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7847: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7848: my $host=&hostname($homeserver);
1.706 raeburn 7849: my $cmd = '';
7850: my $maxtries = 1;
1.800 albertel 7851: foreach my $affiliate (keys(%{$affiliatesref})) {
7852: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7853: }
7854: $cmd =~ s/%%$//;
7855: $cmd = &escape($cmd);
7856: my $query = 'institutionalphotos';
7857: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7858: unless ($queryid=~/^\Q$host\E\_/) {
7859: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7860: return 'error: '.$queryid;
7861: }
7862: my $reply = &get_query_reply($queryid);
7863: my $tries = 1;
7864: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7865: $reply = &get_query_reply($queryid);
7866: $tries ++;
7867: }
7868: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7869: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7870: } else {
7871: my @responses = split(/:/,$reply);
7872: my $outcome = shift(@responses);
7873: foreach my $item (@responses) {
7874: my ($key,$value) = split(/=/,$item);
7875: $$photo{$key} = $value;
7876: }
7877: return $outcome;
7878: }
7879: return 'error';
7880: }
7881:
1.521 raeburn 7882: sub auto_instcode_format {
1.793 albertel 7883: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7884: $cat_order) = @_;
1.521 raeburn 7885: my $courses = '';
1.772 raeburn 7886: my @homeservers;
1.521 raeburn 7887: if ($caller eq 'global') {
1.841 albertel 7888: my %servers = &get_servers($codedom,'library');
7889: foreach my $tryserver (keys(%servers)) {
7890: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7891: push(@homeservers,$tryserver);
7892: }
1.584 raeburn 7893: }
1.1022 raeburn 7894: } elsif ($caller eq 'requests') {
7895: if ($codedom =~ /^$match_domain$/) {
7896: my $chome = &domain($codedom,'primary');
7897: unless ($chome eq 'no_host') {
7898: push(@homeservers,$chome);
7899: }
7900: }
1.521 raeburn 7901: } else {
1.772 raeburn 7902: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7903: }
1.793 albertel 7904: foreach my $code (keys(%{$instcodes})) {
7905: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7906: }
7907: chop($courses);
1.772 raeburn 7908: my $ok_response = 0;
7909: my $response;
7910: while (@homeservers > 0 && $ok_response == 0) {
7911: my $server = shift(@homeservers);
7912: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7913: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7914: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7915: split(/:/,$response);
1.772 raeburn 7916: %{$codes} = (%{$codes},&str2hash($codes_str));
7917: push(@{$codetitles},&str2array($codetitles_str));
7918: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7919: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7920: $ok_response = 1;
7921: }
7922: }
7923: if ($ok_response) {
1.521 raeburn 7924: return 'ok';
1.772 raeburn 7925: } else {
7926: return $response;
1.521 raeburn 7927: }
7928: }
7929:
1.792 raeburn 7930: sub auto_instcode_defaults {
7931: my ($domain,$returnhash,$code_order) = @_;
7932: my @homeservers;
1.841 albertel 7933:
7934: my %servers = &get_servers($domain,'library');
7935: foreach my $tryserver (keys(%servers)) {
7936: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7937: push(@homeservers,$tryserver);
7938: }
1.792 raeburn 7939: }
1.841 albertel 7940:
1.792 raeburn 7941: my $response;
1.841 albertel 7942: foreach my $server (@homeservers) {
1.792 raeburn 7943: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7944: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7945:
7946: foreach my $pair (split(/\&/,$response)) {
7947: my ($name,$value)=split(/\=/,$pair);
7948: if ($name eq 'code_order') {
7949: @{$code_order} = split(/\&/,&unescape($value));
7950: } else {
7951: $returnhash->{&unescape($name)}=&unescape($value);
7952: }
7953: }
7954: return 'ok';
1.792 raeburn 7955: }
1.841 albertel 7956:
7957: return $response;
1.1003 raeburn 7958: }
7959:
7960: sub auto_possible_instcodes {
1.1007 raeburn 7961: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7962: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7963: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7964: return;
7965: }
1.1003 raeburn 7966: my (@homeservers,$uhome);
7967: if (defined(&domain($domain,'primary'))) {
7968: $uhome=&domain($domain,'primary');
7969: push(@homeservers,&domain($domain,'primary'));
7970: } else {
7971: my %servers = &get_servers($domain,'library');
7972: foreach my $tryserver (keys(%servers)) {
7973: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7974: push(@homeservers,$tryserver);
7975: }
7976: }
7977: }
7978: my $response;
7979: foreach my $server (@homeservers) {
7980: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7981: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7982: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7983: split(':',$response);
7984: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7985: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7986: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7987: my ($name,$value)=split('=',$item);
7988: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7989: }
7990: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7991: my ($name,$value)=split('=',$item);
7992: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7993: }
7994: return 'ok';
7995: }
7996: return $response;
7997: }
1.792 raeburn 7998:
1.1010 raeburn 7999: sub auto_courserequest_checks {
8000: my ($dom) = @_;
1.1020 raeburn 8001: my ($homeserver,%validations);
8002: if ($dom =~ /^$match_domain$/) {
8003: $homeserver = &domain($dom,'primary');
8004: }
8005: unless ($homeserver eq 'no_host') {
8006: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8007: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8008: my @items = split(/&/,$response);
8009: foreach my $item (@items) {
8010: my ($key,$value) = split('=',$item);
8011: $validations{&unescape($key)} = &thaw_unescape($value);
8012: }
8013: }
8014: }
1.1010 raeburn 8015: return %validations;
8016: }
8017:
1.1020 raeburn 8018: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8019: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8020: my ($homeserver,$response);
8021: if ($dom =~ /^$match_domain$/) {
8022: $homeserver = &domain($dom,'primary');
8023: }
1.1172.2.43 raeburn 8024: unless ($homeserver eq 'no_host') {
8025: my $customdata;
8026: if (ref($custominfo) eq 'HASH') {
8027: $customdata = &freeze_escape($custominfo);
8028: }
1.1020 raeburn 8029: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8030: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8031: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8032: $customdata,$homeserver));
1.1020 raeburn 8033: }
8034: return $response;
8035: }
8036:
1.777 albertel 8037: sub auto_validate_class_sec {
1.918 raeburn 8038: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8039: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8040: my $ownerlist;
8041: if (ref($owners) eq 'ARRAY') {
8042: $ownerlist = join(',',@{$owners});
8043: } else {
8044: $ownerlist = $owners;
8045: }
1.773 raeburn 8046: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8047: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8048: return $response;
8049: }
8050:
1.1172.2.38 raeburn 8051: sub auto_crsreq_update {
8052: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8053: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8054: my ($homeserver,%crsreqresponse);
8055: if ($cdom =~ /^$match_domain$/) {
8056: $homeserver = &domain($cdom,'primary');
8057: }
8058: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8059: my $info;
8060: if (ref($inbound) eq 'HASH') {
8061: $info = &freeze_escape($inbound);
8062: }
8063: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8064: ':'.&escape($action).':'.&escape($ownername).':'.
8065: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8066: &escape($title).':'.&escape($code).':'.
8067: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8068: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8069: my @items = split(/&/,$response);
8070: foreach my $item (@items) {
8071: my ($key,$value) = split('=',$item);
8072: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8073: }
8074: }
8075: }
8076: return \%crsreqresponse;
8077: }
8078:
1.679 raeburn 8079: # ------------------------------------------------------- Course Group routines
8080:
8081: sub get_coursegroups {
1.809 raeburn 8082: my ($cdom,$cnum,$group,$namespace) = @_;
8083: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8084: }
8085:
1.679 raeburn 8086: sub modify_coursegroup {
8087: my ($cdom,$cnum,$groupsettings) = @_;
8088: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8089: }
8090:
1.809 raeburn 8091: sub toggle_coursegroup_status {
8092: my ($cdom,$cnum,$group,$action) = @_;
8093: my ($from_namespace,$to_namespace);
8094: if ($action eq 'delete') {
8095: $from_namespace = 'coursegroups';
8096: $to_namespace = 'deleted_groups';
8097: } else {
8098: $from_namespace = 'deleted_groups';
8099: $to_namespace = 'coursegroups';
8100: }
8101: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8102: if (my $tmp = &error(%curr_group)) {
8103: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8104: return ('read error',$tmp);
8105: } else {
8106: my %savedsettings = %curr_group;
1.809 raeburn 8107: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8108: my $deloutcome;
8109: if ($result eq 'ok') {
1.809 raeburn 8110: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8111: } else {
8112: return ('write error',$result);
8113: }
8114: if ($deloutcome eq 'ok') {
8115: return 'ok';
8116: } else {
8117: return ('delete error',$deloutcome);
8118: }
8119: }
8120: }
8121:
1.679 raeburn 8122: sub modify_group_roles {
1.957 raeburn 8123: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8124: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8125: my $role = 'gr/'.&escape($userprivs);
8126: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8127: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8128: if ($result eq 'ok') {
8129: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8130: }
1.679 raeburn 8131: return $result;
8132: }
8133:
8134: sub modify_coursegroup_membership {
8135: my ($cdom,$cnum,$membership) = @_;
8136: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8137: return $result;
8138: }
8139:
1.682 raeburn 8140: sub get_active_groups {
8141: my ($udom,$uname,$cdom,$cnum) = @_;
8142: my $now = time;
8143: my %groups = ();
8144: foreach my $key (keys(%env)) {
1.811 albertel 8145: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8146: my ($start,$end) = split(/\./,$env{$key});
8147: if (($end!=0) && ($end<$now)) { next; }
8148: if (($start!=0) && ($start>$now)) { next; }
8149: if ($1 eq $cdom && $2 eq $cnum) {
8150: $groups{$3} = $env{$key} ;
8151: }
8152: }
8153: }
8154: return %groups;
8155: }
8156:
1.683 raeburn 8157: sub get_group_membership {
8158: my ($cdom,$cnum,$group) = @_;
8159: return(&dump('groupmembership',$cdom,$cnum,$group));
8160: }
8161:
8162: sub get_users_groups {
8163: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8164: my @usersgroups;
1.683 raeburn 8165: my $cachetime=1800;
8166:
8167: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8168: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8169: if (defined($cached)) {
1.734 albertel 8170: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8171: } else {
8172: $grouplist = '';
1.816 raeburn 8173: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8174: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8175: my $access_end = $env{'course.'.$courseid.
8176: '.default_enrollment_end_date'};
8177: my $now = time;
8178: foreach my $key (keys(%roleshash)) {
8179: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8180: my $group = $1;
8181: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8182: my $start = $2;
8183: my $end = $1;
8184: if ($start == -1) { next; } # deleted from group
8185: if (($start!=0) && ($start>$now)) { next; }
8186: if (($end!=0) && ($end<$now)) {
8187: if ($access_end && $access_end < $now) {
8188: if ($access_end - $end < 86400) {
8189: push(@usersgroups,$group);
1.733 raeburn 8190: }
8191: }
1.817 raeburn 8192: next;
1.733 raeburn 8193: }
1.817 raeburn 8194: push(@usersgroups,$group);
1.683 raeburn 8195: }
8196: }
8197: }
1.817 raeburn 8198: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8199: $grouplist = join(':',@usersgroups);
8200: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8201: }
1.733 raeburn 8202: return @usersgroups;
1.683 raeburn 8203: }
8204:
8205: sub devalidate_getgroups_cache {
8206: my ($udom,$uname,$cdom,$cnum)=@_;
8207: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8208:
1.683 raeburn 8209: my $hashid="$udom:$uname:$courseid";
8210: &devalidate_cache_new('getgroups',$hashid);
8211: }
8212:
1.12 www 8213: # ------------------------------------------------------------------ Plain Text
8214:
8215: sub plaintext {
1.988 raeburn 8216: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8217: if ($short =~ m{^cr/}) {
1.758 albertel 8218: return (split('/',$short))[-1];
8219: }
1.742 raeburn 8220: if (!defined($cid)) {
8221: $cid = $env{'request.course.id'};
8222: }
8223: my %rolenames = (
1.1008 raeburn 8224: Course => 'std',
8225: Community => 'alt1',
1.742 raeburn 8226: );
1.1037 raeburn 8227: if ($cid ne '') {
8228: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8229: unless ($forcedefault) {
8230: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8231: &Apache::lonlocal::mt_escape(\$roletext);
8232: return &Apache::lonlocal::mt($roletext);
8233: }
8234: }
8235: }
8236: if ((defined($type)) && (defined($rolenames{$type})) &&
8237: (defined($rolenames{$type})) &&
8238: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8239: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8240: } elsif ($cid ne '') {
8241: my $crstype = $env{'course.'.$cid.'.type'};
8242: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8243: (defined($prp{$short}{$rolenames{$crstype}}))) {
8244: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8245: }
1.742 raeburn 8246: }
1.1037 raeburn 8247: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8248: }
8249:
8250: # ----------------------------------------------------------------- Assign Role
8251:
8252: sub assignrole {
1.957 raeburn 8253: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8254: $context)=@_;
1.21 www 8255: my $mrole;
8256: if ($role =~ /^cr\//) {
1.393 www 8257: my $cwosec=$url;
1.811 albertel 8258: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8259: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8260: my $refused = 1;
8261: if ($context eq 'requestcourses') {
8262: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8263: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8264: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8265: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8266: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8267: if ($crsenv{'internal.courseowner'} eq
8268: $env{'user.name'}.':'.$env{'user.domain'}) {
8269: $refused = '';
8270: }
8271: }
8272: }
8273: }
8274: }
8275: if ($refused) {
8276: &logthis('Refused custom assignrole: '.
8277: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8278: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8279: return 'refused';
8280: }
1.104 www 8281: }
1.21 www 8282: $mrole='cr';
1.678 raeburn 8283: } elsif ($role =~ /^gr\//) {
8284: my $cwogrp=$url;
1.811 albertel 8285: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8286: unless (&allowed('mdg',$cwogrp)) {
8287: &logthis('Refused group assignrole: '.
8288: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8289: $env{'user.name'}.' at '.$env{'user.domain'});
8290: return 'refused';
8291: }
8292: $mrole='gr';
1.21 www 8293: } else {
1.82 www 8294: my $cwosec=$url;
1.811 albertel 8295: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8296: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8297: my $refused;
8298: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8299: if (!(&allowed('c'.$role,$url))) {
8300: $refused = 1;
8301: }
8302: } else {
8303: $refused = 1;
8304: }
1.947 raeburn 8305: if ($refused) {
1.1045 raeburn 8306: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8307: if (!$selfenroll && $context eq 'course') {
8308: my %crsenv;
8309: if ($role eq 'cc' || $role eq 'co') {
8310: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8311: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8312: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8313: if ($crsenv{'internal.courseowner'} eq
8314: $env{'user.name'}.':'.$env{'user.domain'}) {
8315: $refused = '';
8316: }
8317: }
8318: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8319: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8320: if ($crsenv{'internal.courseowner'} eq
8321: $env{'user.name'}.':'.$env{'user.domain'}) {
8322: $refused = '';
8323: }
8324: }
8325: }
8326: }
8327: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8328: $refused = '';
1.1017 raeburn 8329: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8330: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8331: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8332: my $wrongcc;
8333: if ($cnum =~ /^$match_community$/) {
8334: $wrongcc = 1 if ($role eq 'cc');
8335: } else {
8336: $wrongcc = 1 if ($role eq 'co');
8337: }
8338: unless ($wrongcc) {
8339: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8340: if ($crsenv{'internal.courseowner'} eq
8341: $env{'user.name'}.':'.$env{'user.domain'}) {
8342: $refused = '';
8343: }
1.1017 raeburn 8344: }
8345: }
1.1172.2.9 raeburn 8346: } elsif ($context eq 'requestauthor') {
8347: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8348: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8349: if ($env{'environment.requestauthor'} eq 'automatic') {
8350: $refused = '';
8351: } else {
8352: my %domdefaults = &get_domain_defaults($udom);
8353: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8354: my $checkbystatus;
8355: if ($env{'user.adv'}) {
8356: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8357: if ($disposition eq 'automatic') {
8358: $refused = '';
8359: } elsif ($disposition eq '') {
8360: $checkbystatus = 1;
8361: }
8362: } else {
8363: $checkbystatus = 1;
8364: }
8365: if ($checkbystatus) {
8366: if ($env{'environment.inststatus'}) {
8367: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8368: foreach my $type (@inststatuses) {
8369: if (($type ne '') &&
8370: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8371: $refused = '';
8372: }
8373: }
8374: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8375: $refused = '';
8376: }
8377: }
8378: }
8379: }
8380: }
1.1017 raeburn 8381: }
8382: if ($refused) {
1.947 raeburn 8383: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8384: ' '.$role.' '.$end.' '.$start.' by '.
8385: $env{'user.name'}.' at '.$env{'user.domain'});
8386: return 'refused';
8387: }
1.932 raeburn 8388: }
1.1131 raeburn 8389: } elsif ($role eq 'au') {
8390: if ($url ne '/'.$udom.'/') {
8391: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8392: ' to assign author role for '.$uname.':'.$udom.
8393: ' in domain: '.$url.' refused (wrong domain).');
8394: return 'refused';
8395: }
1.104 www 8396: }
1.21 www 8397: $mrole=$role;
8398: }
1.620 albertel 8399: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8400: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8401: if ($end) { $command.='_'.$end; }
1.21 www 8402: if ($start) {
8403: if ($end) {
1.81 www 8404: $command.='_'.$start;
1.21 www 8405: } else {
1.81 www 8406: $command.='_0_'.$start;
1.21 www 8407: }
8408: }
1.739 raeburn 8409: my $origstart = $start;
8410: my $origend = $end;
1.957 raeburn 8411: my $delflag;
1.357 www 8412: # actually delete
8413: if ($deleteflag) {
1.373 www 8414: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8415: # modify command to delete the role
1.620 albertel 8416: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8417: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8418: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8419: # set start and finish to negative values for userrolelog
8420: $start=-1;
8421: $end=-1;
1.957 raeburn 8422: $delflag = 1;
1.357 www 8423: }
8424: }
8425: # send command
1.349 www 8426: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8427: # log new user role if status is ok
1.349 www 8428: if ($answer eq 'ok') {
1.663 raeburn 8429: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8430: if (($role eq 'cc') || ($role eq 'in') ||
8431: ($role eq 'ep') || ($role eq 'ad') ||
8432: ($role eq 'ta') || ($role eq 'st') ||
8433: ($role=~/^cr/) || ($role eq 'gr') ||
8434: ($role eq 'co')) {
1.1172.2.13 raeburn 8435: # for course roles, perform group memberships changes triggered by role change.
8436: unless ($role =~ /^gr/) {
8437: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8438: $origstart,$selfenroll,$context);
8439: }
1.1172.2.9 raeburn 8440: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8441: $selfenroll,$context);
8442: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8443: ($role eq 'au') || ($role eq 'dc')) {
8444: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8445: $context);
8446: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8447: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8448: $context);
8449: }
1.1053 raeburn 8450: if ($role eq 'cc') {
8451: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8452: }
1.349 www 8453: }
8454: return $answer;
1.169 harris41 8455: }
8456:
1.1053 raeburn 8457: sub autoupdate_coowners {
8458: my ($url,$end,$start,$uname,$udom) = @_;
8459: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8460: if (($cdom ne '') && ($cnum ne '')) {
8461: my $now = time;
8462: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8463: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8464: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8465: my $instcode = $coursehash{'internal.coursecode'};
8466: if ($instcode ne '') {
1.1056 raeburn 8467: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8468: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8469: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8470: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8471: if ($result eq 'valid') {
8472: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8473: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8474: push(@newcoowners,$coowner);
8475: }
8476: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8477: push(@newcoowners,$uname.':'.$udom);
8478: }
8479: @newcoowners = sort(@newcoowners);
8480: } else {
8481: push(@newcoowners,$uname.':'.$udom);
8482: }
8483: } else {
8484: if ($coursehash{'internal.co-owners'}) {
8485: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8486: unless ($coowner eq $uname.':'.$udom) {
8487: push(@newcoowners,$coowner);
8488: }
8489: }
8490: unless (@newcoowners > 0) {
8491: $delcoowners = 1;
8492: $coowners = '';
8493: }
8494: }
8495: }
8496: if (@newcoowners || $delcoowners) {
8497: &store_coowners($cdom,$cnum,$coursehash{'home'},
8498: $delcoowners,@newcoowners);
8499: }
8500: }
8501: }
8502: }
8503: }
8504: }
8505: }
8506:
8507: sub store_coowners {
8508: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8509: my $cid = $cdom.'_'.$cnum;
8510: my ($coowners,$delresult,$putresult);
8511: if (@newcoowners) {
8512: $coowners = join(',',@newcoowners);
8513: my %coownershash = (
8514: 'internal.co-owners' => $coowners,
8515: );
8516: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8517: if ($putresult eq 'ok') {
8518: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8519: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8520: }
8521: }
8522: }
8523: if ($delcoowners) {
8524: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8525: if ($delresult eq 'ok') {
8526: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8527: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8528: }
8529: }
8530: }
8531: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8532: my %crsinfo =
8533: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8534: if (ref($crsinfo{$cid}) eq 'HASH') {
8535: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8536: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8537: }
8538: }
8539: }
8540:
1.169 harris41 8541: # -------------------------------------------------- Modify user authentication
1.197 www 8542: # Overrides without validation
8543:
1.169 harris41 8544: sub modifyuserauth {
8545: my ($udom,$uname,$umode,$upass)=@_;
8546: my $uhome=&homeserver($uname,$udom);
1.197 www 8547: unless (&allowed('mau',$udom)) { return 'refused'; }
8548: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8549: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8550: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8551: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8552: &escape($upass),$uhome);
1.620 albertel 8553: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8554: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8555: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8556: &log($udom,,$uname,$uhome,
1.620 albertel 8557: 'Authentication changed by '.$env{'user.domain'}.', '.
8558: $env{'user.name'}.', '.$umode.
1.197 www 8559: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8560: unless ($reply eq 'ok') {
1.197 www 8561: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8562: return 'error: '.$reply;
8563: }
1.170 harris41 8564: return 'ok';
1.80 www 8565: }
8566:
1.81 www 8567: # --------------------------------------------------------------- Modify a user
1.80 www 8568:
1.81 www 8569: sub modifyuser {
1.206 matthew 8570: my ($udom, $uname, $uid,
8571: $umode, $upass, $first,
8572: $middle, $last, $gene,
1.1058 raeburn 8573: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8574: $udom= &LONCAPA::clean_domain($udom);
8575: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8576: my $showcandelete = 'none';
8577: if (ref($candelete) eq 'ARRAY') {
8578: if (@{$candelete} > 0) {
8579: $showcandelete = join(', ',@{$candelete});
8580: }
8581: }
1.81 www 8582: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8583: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8584: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8585: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8586: ' desiredhome not specified').
1.620 albertel 8587: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8588: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8589: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8590: my $newuser;
8591: if ($uhome eq 'no_host') {
8592: $newuser = 1;
8593: }
1.80 www 8594: # ----------------------------------------------------------------- Create User
1.406 albertel 8595: if (($uhome eq 'no_host') &&
8596: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8597: my $unhome='';
1.844 albertel 8598: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8599: $unhome = $desiredhome;
1.620 albertel 8600: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8601: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8602: } else { # load balancing routine for determining $unhome
1.81 www 8603: my $loadm=10000000;
1.841 albertel 8604: my %servers = &get_servers($udom,'library');
8605: foreach my $tryserver (keys(%servers)) {
8606: my $answer=reply('load',$tryserver);
8607: if (($answer=~/\d+/) && ($answer<$loadm)) {
8608: $loadm=$answer;
8609: $unhome=$tryserver;
8610: }
1.80 www 8611: }
8612: }
8613: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8614: return 'error: unable to find a home server for '.$uname.
8615: ' in domain '.$udom;
1.80 www 8616: }
8617: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8618: &escape($upass),$unhome);
8619: unless ($reply eq 'ok') {
8620: return 'error: '.$reply;
8621: }
1.230 stredwic 8622: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8623: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8624: return 'error: unable verify users home machine.';
1.80 www 8625: }
1.209 matthew 8626: } # End of creation of new user
1.80 www 8627: # ---------------------------------------------------------------------- Add ID
8628: if ($uid) {
8629: $uid=~tr/A-Z/a-z/;
8630: my %uidhash=&idrget($udom,$uname);
1.196 www 8631: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8632: && (!$forceid)) {
1.80 www 8633: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8634: return 'error: user id "'.$uid.'" does not match '.
8635: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8636: }
8637: } else {
8638: &idput($udom,($uname => $uid));
8639: }
8640: }
8641: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8642: my @tmp=&get('environment',
1.899 raeburn 8643: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8644: 'permanentemail','inststatus'],
1.134 albertel 8645: $udom,$uname);
1.1075 raeburn 8646: my (%names,%oldnames);
1.313 matthew 8647: if ($tmp[0] =~ m/^error:.*/) {
8648: %names=();
8649: } else {
8650: %names = @tmp;
1.1075 raeburn 8651: %oldnames = %names;
1.313 matthew 8652: }
1.388 www 8653: #
1.1058 raeburn 8654: # If name, email and/or uid are blank (e.g., because an uploaded file
8655: # of users did not contain them), do not overwrite existing values
8656: # unless field is in $candelete array ref.
8657: #
8658:
8659: my @fields = ('firstname','middlename','lastname','generation',
8660: 'permanentemail','id');
8661: my %newvalues;
8662: if (ref($candelete) eq 'ARRAY') {
8663: foreach my $field (@fields) {
8664: if (grep(/^\Q$field\E$/,@{$candelete})) {
8665: if ($field eq 'firstname') {
8666: $names{$field} = $first;
8667: } elsif ($field eq 'middlename') {
8668: $names{$field} = $middle;
8669: } elsif ($field eq 'lastname') {
8670: $names{$field} = $last;
8671: } elsif ($field eq 'generation') {
8672: $names{$field} = $gene;
8673: } elsif ($field eq 'permanentemail') {
8674: $names{$field} = $email;
8675: } elsif ($field eq 'id') {
8676: $names{$field} = $uid;
8677: }
8678: }
8679: }
8680: }
1.388 www 8681: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8682: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8683: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8684: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8685: if ($email) {
8686: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8687: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8688: }
1.899 raeburn 8689: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8690: if (defined($inststatus)) {
8691: $names{'inststatus'} = '';
8692: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8693: if (ref($usertypes) eq 'HASH') {
8694: my @okstatuses;
8695: foreach my $item (split(/:/,$inststatus)) {
8696: if (defined($usertypes->{$item})) {
8697: push(@okstatuses,$item);
8698: }
8699: }
8700: if (@okstatuses) {
8701: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8702: }
8703: }
8704: }
1.1075 raeburn 8705: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8706: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8707: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8708: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8709: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8710: } else {
8711: $logmsg .= ' during self creation';
8712: }
1.1075 raeburn 8713: my $changed;
8714: if ($newuser) {
8715: $changed = 1;
8716: } else {
8717: foreach my $field (@fields) {
8718: if ($names{$field} ne $oldnames{$field}) {
8719: $changed = 1;
8720: last;
8721: }
8722: }
8723: }
8724: unless ($changed) {
8725: $logmsg = 'No changes in user information needed for: '.$logmsg;
8726: &logthis($logmsg);
8727: return 'ok';
8728: }
8729: my $reply = &put('environment', \%names, $udom,$uname);
8730: if ($reply ne 'ok') {
8731: return 'error: '.$reply;
8732: }
1.1087 raeburn 8733: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8734: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8735: }
1.1075 raeburn 8736: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8737: &devalidate_cache_new('namescache',$uname.':'.$udom);
8738: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8739: &logthis($logmsg);
1.134 albertel 8740: return 'ok';
1.80 www 8741: }
8742:
1.81 www 8743: # -------------------------------------------------------------- Modify student
1.80 www 8744:
1.81 www 8745: sub modifystudent {
8746: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8747: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8748: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8749: if (!$cid) {
1.620 albertel 8750: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8751: return 'not_in_class';
8752: }
1.80 www 8753: }
8754: # --------------------------------------------------------------- Make the user
1.81 www 8755: my $reply=&modifyuser
1.209 matthew 8756: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8757: $desiredhome,$email,$inststatus);
1.80 www 8758: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8759: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8760: # student's environment
1.297 matthew 8761: $uid = undef if (!$forceid);
1.455 albertel 8762: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8763: $gene,$usec,$end,$start,$type,$locktype,
8764: $cid,$selfenroll,$context,$credits);
1.297 matthew 8765: return $reply;
8766: }
8767:
8768: sub modify_student_enrollment {
1.1172.2.23 raeburn 8769: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8770: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8771: my ($cdom,$cnum,$chome);
8772: if (!$cid) {
1.620 albertel 8773: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8774: return 'not_in_class';
8775: }
1.620 albertel 8776: $cdom=$env{'course.'.$cid.'.domain'};
8777: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8778: } else {
8779: ($cdom,$cnum)=split(/_/,$cid);
8780: }
1.620 albertel 8781: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8782: if (!$chome) {
1.457 raeburn 8783: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8784: }
1.455 albertel 8785: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8786: # Make sure the user exists
1.81 www 8787: my $uhome=&homeserver($uname,$udom);
8788: if (($uhome eq '') || ($uhome eq 'no_host')) {
8789: return 'error: no such user';
8790: }
1.297 matthew 8791: # Get student data if we were not given enough information
8792: if (!defined($first) || $first eq '' ||
8793: !defined($last) || $last eq '' ||
8794: !defined($uid) || $uid eq '' ||
8795: !defined($middle) || $middle eq '' ||
8796: !defined($gene) || $gene eq '') {
1.294 matthew 8797: # They did not supply us with enough data to enroll the student, so
8798: # we need to pick up more information.
1.297 matthew 8799: my %tmp = &get('environment',
1.294 matthew 8800: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8801: ,$udom,$uname);
8802:
1.800 albertel 8803: #foreach my $key (keys(%tmp)) {
8804: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8805: #}
1.294 matthew 8806: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8807: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8808: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8809: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8810: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8811: }
1.556 albertel 8812: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8813: my $user = "$uname:$udom";
8814: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8815: my $reply=cput('classlist',
1.1148 raeburn 8816: {$user =>
1.1172.2.19 raeburn 8817: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8818: $cdom,$cnum);
1.1148 raeburn 8819: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8820: &devalidate_getsection_cache($udom,$uname,$cid);
8821: } else {
1.81 www 8822: return 'error: '.$reply;
8823: }
1.297 matthew 8824: # Add student role to user
1.83 www 8825: my $uurl='/'.$cid;
1.81 www 8826: $uurl=~s/\_/\//g;
8827: if ($usec) {
8828: $uurl.='/'.$usec;
8829: }
1.1148 raeburn 8830: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8831: $selfenroll,$context);
8832: if ($result ne 'ok') {
8833: if ($old_entry{$user} ne '') {
8834: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8835: } else {
8836: $reply = &del('classlist',[$user],$cdom,$cnum);
8837: }
8838: }
8839: return $result;
1.21 www 8840: }
8841:
1.556 albertel 8842: sub format_name {
8843: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8844: my $name;
8845: if ($first ne 'lastname') {
8846: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8847: } else {
8848: if ($lastname=~/\S/) {
8849: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8850: $name=~s/\s+,/,/;
8851: } else {
8852: $name.= $firstname.' '.$middlename.' '.$generation;
8853: }
8854: }
8855: $name=~s/^\s+//;
8856: $name=~s/\s+$//;
8857: $name=~s/\s+/ /g;
8858: return $name;
8859: }
8860:
1.84 www 8861: # ------------------------------------------------- Write to course preferences
8862:
8863: sub writecoursepref {
8864: my ($courseid,%prefs)=@_;
8865: $courseid=~s/^\///;
8866: $courseid=~s/\_/\//g;
8867: my ($cdomain,$cnum)=split(/\//,$courseid);
8868: my $chome=homeserver($cnum,$cdomain);
8869: if (($chome eq '') || ($chome eq 'no_host')) {
8870: return 'error: no such course';
8871: }
8872: my $cstring='';
1.800 albertel 8873: foreach my $pref (keys(%prefs)) {
8874: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8875: }
1.84 www 8876: $cstring=~s/\&$//;
8877: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8878: }
8879:
8880: # ---------------------------------------------------------- Make/modify course
8881:
8882: sub createcourse {
1.741 raeburn 8883: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8884: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8885: $url=&declutter($url);
8886: my $cid='';
1.1028 raeburn 8887: if ($context eq 'requestcourses') {
8888: my $can_create = 0;
8889: my ($ownername,$ownerdom) = split(':',$course_owner);
8890: if ($udom eq $ownerdom) {
8891: if (&usertools_access($ownername,$ownerdom,$category,undef,
8892: $context)) {
8893: $can_create = 1;
8894: }
8895: } else {
8896: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8897: $category);
8898: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8899: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8900: if (@curr > 0) {
8901: my @options = qw(approval validate autolimit);
8902: my $optregex = join('|',@options);
8903: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8904: $can_create = 1;
8905: }
8906: }
8907: }
8908: }
8909: if ($can_create) {
8910: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8911: unless (&allowed('ccc',$udom)) {
8912: return 'refused';
8913: }
1.1017 raeburn 8914: }
8915: } else {
8916: return 'refused';
8917: }
1.1028 raeburn 8918: } elsif (!&allowed('ccc',$udom)) {
8919: return 'refused';
1.84 www 8920: }
1.1011 raeburn 8921: # --------------------------------------------------------------- Get Unique ID
8922: my $uname;
8923: if ($cnum =~ /^$match_courseid$/) {
8924: my $chome=&homeserver($cnum,$udom,'true');
8925: if (($chome eq '') || ($chome eq 'no_host')) {
8926: $uname = $cnum;
8927: } else {
1.1038 raeburn 8928: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8929: }
8930: } else {
1.1038 raeburn 8931: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8932: }
8933: return $uname if ($uname =~ /^error/);
8934: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8935: if (!defined($course_server)) {
8936: if (defined(&domain($udom,'primary'))) {
8937: $course_server = &domain($udom,'primary');
8938: } else {
8939: $course_server = $env{'user.home'};
8940: }
8941: }
8942: my %host_servers =
8943: &Apache::lonnet::get_servers($udom,'library');
8944: unless ($host_servers{$course_server}) {
8945: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8946: }
1.84 www 8947: # ------------------------------------------------------------- Make the course
8948: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8949: $course_server);
1.84 www 8950: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8951: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8952: if (($uhome eq '') || ($uhome eq 'no_host')) {
8953: return 'error: no such course';
8954: }
1.271 www 8955: # ----------------------------------------------------------------- Course made
1.516 raeburn 8956: # log existence
1.1029 raeburn 8957: my $now = time;
1.918 raeburn 8958: my $newcourse = {
8959: $udom.'_'.$uname => {
1.921 raeburn 8960: description => $description,
8961: inst_code => $inst_code,
8962: owner => $course_owner,
8963: type => $crstype,
1.1029 raeburn 8964: creator => $env{'user.name'}.':'.
8965: $env{'user.domain'},
8966: created => $now,
8967: context => $context,
1.918 raeburn 8968: },
8969: };
1.921 raeburn 8970: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8971: # set toplevel url
1.271 www 8972: my $topurl=$url;
8973: unless ($nonstandard) {
8974: # ------------------------------------------ For standard courses, make top url
8975: my $mapurl=&clutter($url);
1.278 www 8976: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8977: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8978: <map>
8979: <resource id="1" type="start"></resource>
8980: <resource id="2" src="$mapurl"></resource>
8981: <resource id="3" type="finish"></resource>
8982: <link index="1" from="1" to="2"></link>
8983: <link index="2" from="2" to="3"></link>
8984: </map>
8985: ENDINITMAP
8986: $topurl=&declutter(
1.638 albertel 8987: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8988: );
8989: }
8990: # ----------------------------------------------------------- Write preferences
1.84 www 8991: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8992: ('description' => $description,
8993: 'url' => $topurl,
8994: 'internal.creator' => $env{'user.name'}.':'.
8995: $env{'user.domain'},
8996: 'internal.created' => $now,
8997: 'internal.creationcontext' => $context)
8998: );
1.84 www 8999: return '/'.$udom.'/'.$uname;
9000: }
9001:
1.1011 raeburn 9002: # ------------------------------------------------------------------- Create ID
9003: sub generate_coursenum {
1.1038 raeburn 9004: my ($udom,$crstype) = @_;
1.1011 raeburn 9005: my $domdesc = &domain($udom);
9006: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9007: my $first;
9008: if ($crstype eq 'Community') {
9009: $first = '0';
9010: } else {
9011: $first = int(1+rand(9));
9012: }
9013: my $uname=$first.
1.1011 raeburn 9014: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9015: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9016: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9017: # ----------------------------------------------- Make sure that does not exist
9018: my $uhome=&homeserver($uname,$udom,'true');
9019: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9020: if ($crstype eq 'Community') {
9021: $first = '0';
9022: } else {
9023: $first = int(1+rand(9));
9024: }
9025: $uname=$first.
1.1011 raeburn 9026: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9027: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9028: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9029: $uhome=&homeserver($uname,$udom,'true');
9030: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9031: return 'error: unable to generate unique course-ID';
9032: }
9033: }
9034: return $uname;
9035: }
9036:
1.813 albertel 9037: sub is_course {
1.1167 droeschl 9038: my ($cdom, $cnum) = scalar(@_) == 1 ?
9039: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9040:
9041: return unless $cdom and $cnum;
9042:
9043: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9044: '.');
9045:
1.1172.2.23 raeburn 9046: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9047: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9048: }
9049:
1.1015 raeburn 9050: sub store_userdata {
9051: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9052: my $result;
1.1016 raeburn 9053: if ($datakey ne '') {
1.1013 raeburn 9054: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9055: if ($udom eq '' || $uname eq '') {
9056: $udom = $env{'user.domain'};
9057: $uname = $env{'user.name'};
9058: }
9059: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9060: if (($uhome eq '') || ($uhome eq 'no_host')) {
9061: $result = 'error: no_host';
9062: } else {
9063: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9064: $storehash->{'host'} = $perlvar{'lonHostID'};
9065:
9066: my $namevalue='';
9067: foreach my $key (keys(%{$storehash})) {
9068: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9069: }
9070: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9071: unless ($namespace eq 'courserequests') {
9072: $datakey = &escape($datakey);
9073: }
1.1105 raeburn 9074: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9075: $namevalue,$uhome);
1.1013 raeburn 9076: }
9077: } else {
9078: $result = 'error: data to store was not a hash reference';
9079: }
9080: } else {
9081: $result= 'error: invalid requestkey';
9082: }
9083: return $result;
9084: }
9085:
1.21 www 9086: # ---------------------------------------------------------- Assign Custom Role
9087:
9088: sub assigncustomrole {
1.957 raeburn 9089: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9090: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9091: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9092: }
9093:
9094: # ----------------------------------------------------------------- Revoke Role
9095:
9096: sub revokerole {
1.957 raeburn 9097: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9098: my $now=time;
1.965 raeburn 9099: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9100: }
9101:
9102: # ---------------------------------------------------------- Revoke Custom Role
9103:
9104: sub revokecustomrole {
1.957 raeburn 9105: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9106: my $now=time;
1.357 www 9107: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9108: $deleteflag,$selfenroll,$context);
1.17 www 9109: }
9110:
1.533 banghart 9111: # ------------------------------------------------------------ Disk usage
1.535 albertel 9112: sub diskusage {
1.955 raeburn 9113: my ($udom,$uname,$directorypath,$getpropath)=@_;
9114: $directorypath =~ s/\/$//;
9115: my $listing=&reply('du2:'.&escape($directorypath).':'
9116: .&escape($getpropath).':'.&escape($uname).':'
9117: .&escape($udom),homeserver($uname,$udom));
9118: if ($listing eq 'unknown_cmd') {
9119: if ($getpropath) {
9120: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9121: }
9122: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9123: }
1.514 albertel 9124: return $listing;
1.512 banghart 9125: }
9126:
1.566 banghart 9127: sub is_locked {
1.1096 raeburn 9128: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9129: my @check;
9130: my $is_locked;
1.1093 raeburn 9131: push (@check,$file_name);
1.613 albertel 9132: my %locked = &get('file_permissions',\@check,
1.620 albertel 9133: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9134: my ($tmp)=keys(%locked);
9135: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9136:
1.566 banghart 9137: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9138: $is_locked = 'false';
9139: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9140: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9141: $is_locked = 'true';
1.1096 raeburn 9142: if (ref($which) eq 'ARRAY') {
9143: push(@{$which},$entry);
9144: } else {
9145: last;
9146: }
1.745 raeburn 9147: }
9148: }
1.566 banghart 9149: } else {
9150: $is_locked = 'false';
9151: }
1.1093 raeburn 9152: return $is_locked;
1.566 banghart 9153: }
9154:
1.759 albertel 9155: sub declutter_portfile {
9156: my ($file) = @_;
1.833 albertel 9157: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9158: return $file;
9159: }
9160:
1.559 banghart 9161: # ------------------------------------------------------------- Mark as Read Only
9162:
9163: sub mark_as_readonly {
9164: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9165: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9166: my ($tmp)=keys(%current_permissions);
9167: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9168: foreach my $file (@{$files}) {
1.759 albertel 9169: $file = &declutter_portfile($file);
1.561 banghart 9170: push(@{$current_permissions{$file}},$what);
1.559 banghart 9171: }
1.613 albertel 9172: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9173: return;
9174: }
9175:
1.572 banghart 9176: # ------------------------------------------------------------Save Selected Files
9177:
9178: sub save_selected_files {
9179: my ($user, $path, @files) = @_;
9180: my $filename = $user."savedfiles";
1.573 banghart 9181: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9182: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9183: foreach my $file (@files) {
1.620 albertel 9184: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9185: }
9186: foreach my $file (@other_files) {
1.574 banghart 9187: print (OUT $file."\n");
1.572 banghart 9188: }
1.574 banghart 9189: close (OUT);
1.572 banghart 9190: return 'ok';
9191: }
9192:
1.574 banghart 9193: sub clear_selected_files {
9194: my ($user) = @_;
9195: my $filename = $user."savedfiles";
1.1117 foxr 9196: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9197: print (OUT undef);
9198: close (OUT);
9199: return ("ok");
9200: }
9201:
1.572 banghart 9202: sub files_in_path {
9203: my ($user, $path) = @_;
9204: my $filename = $user."savedfiles";
9205: my %return_files;
1.1117 foxr 9206: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9207: while (my $line_in = <IN>) {
1.574 banghart 9208: chomp ($line_in);
9209: my @paths_and_file = split (m!/!, $line_in);
9210: my $file_part = pop (@paths_and_file);
9211: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9212: $path_part.='/';
9213: my $path_and_file = $path_part.$file_part;
9214: if ($path_part eq $path) {
9215: $return_files{$file_part}= 'selected';
9216: }
9217: }
1.574 banghart 9218: close (IN);
9219: return (\%return_files);
1.572 banghart 9220: }
9221:
9222: # called in portfolio select mode, to show files selected NOT in current directory
9223: sub files_not_in_path {
9224: my ($user, $path) = @_;
9225: my $filename = $user."savedfiles";
9226: my @return_files;
9227: my $path_part;
1.1117 foxr 9228: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9229: while (my $line = <IN>) {
1.572 banghart 9230: #ok, I know it's clunky, but I want it to work
1.800 albertel 9231: my @paths_and_file = split(m|/|, $line);
9232: my $file_part = pop(@paths_and_file);
9233: chomp($file_part);
9234: my $path_part = join('/', @paths_and_file);
1.572 banghart 9235: $path_part .= '/';
9236: my $path_and_file = $path_part.$file_part;
9237: if ($path_part ne $path) {
1.800 albertel 9238: push(@return_files, ($path_and_file));
1.572 banghart 9239: }
9240: }
1.800 albertel 9241: close(OUT);
1.574 banghart 9242: return (@return_files);
1.572 banghart 9243: }
9244:
1.745 raeburn 9245: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9246:
1.745 raeburn 9247: sub get_portfile_permissions {
9248: my ($domain,$user) = @_;
1.613 albertel 9249: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9250: my ($tmp)=keys(%current_permissions);
9251: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9252: return \%current_permissions;
9253: }
9254:
9255: #---------------------------------------------Get portfolio file access controls
9256:
1.749 raeburn 9257: sub get_access_controls {
1.745 raeburn 9258: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9259: my %access;
9260: my $real_file = $file;
9261: $file =~ s/\.meta$//;
1.745 raeburn 9262: if (defined($file)) {
1.749 raeburn 9263: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9264: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9265: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9266: }
9267: }
1.745 raeburn 9268: } else {
1.749 raeburn 9269: foreach my $key (keys(%{$current_permissions})) {
9270: if ($key =~ /\0accesscontrol$/) {
9271: if (defined($group)) {
9272: if ($key !~ m-^\Q$group\E/-) {
9273: next;
9274: }
9275: }
9276: my ($fullpath) = split(/\0/,$key);
9277: if (ref($$current_permissions{$key}) eq 'HASH') {
9278: foreach my $control (keys(%{$$current_permissions{$key}})) {
9279: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9280: }
9281: }
9282: }
9283: }
9284: }
9285: return %access;
9286: }
9287:
9288: sub modify_access_controls {
9289: my ($file_name,$changes,$domain,$user)=@_;
9290: my ($outcome,$deloutcome);
9291: my %store_permissions;
9292: my %new_values;
9293: my %new_control;
9294: my %translation;
9295: my @deletions = ();
9296: my $now = time;
9297: if (exists($$changes{'activate'})) {
9298: if (ref($$changes{'activate'}) eq 'HASH') {
9299: my @newitems = sort(keys(%{$$changes{'activate'}}));
9300: my $numnew = scalar(@newitems);
9301: for (my $i=0; $i<$numnew; $i++) {
9302: my $newkey = $newitems[$i];
9303: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9304: if ($newkey =~ /^\d+:/) {
9305: $newkey =~ s/^(\d+)/$newid/;
9306: $translation{$1} = $newid;
9307: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9308: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9309: $translation{$1} = $newid;
9310: }
1.749 raeburn 9311: $new_values{$file_name."\0".$newkey} =
9312: $$changes{'activate'}{$newitems[$i]};
9313: $new_control{$newkey} = $now;
9314: }
9315: }
9316: }
9317: my %todelete;
9318: my %changed_items;
9319: foreach my $action ('delete','update') {
9320: if (exists($$changes{$action})) {
9321: if (ref($$changes{$action}) eq 'HASH') {
9322: foreach my $key (keys(%{$$changes{$action}})) {
9323: my ($itemnum) = ($key =~ /^([^:]+):/);
9324: if ($action eq 'delete') {
9325: $todelete{$itemnum} = 1;
9326: } else {
9327: $changed_items{$itemnum} = $key;
9328: }
9329: }
1.745 raeburn 9330: }
9331: }
1.749 raeburn 9332: }
9333: # get lock on access controls for file.
9334: my $lockhash = {
9335: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9336: ':'.$env{'user.domain'},
9337: };
9338: my $tries = 0;
9339: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9340:
9341: while (($gotlock ne 'ok') && $tries <3) {
9342: $tries ++;
9343: sleep 1;
9344: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9345: }
9346: if ($gotlock eq 'ok') {
9347: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9348: my ($tmp)=keys(%curr_permissions);
9349: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9350: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9351: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9352: if (ref($curr_controls) eq 'HASH') {
9353: foreach my $control_item (keys(%{$curr_controls})) {
9354: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9355: if (defined($todelete{$itemnum})) {
9356: push(@deletions,$file_name."\0".$control_item);
9357: } else {
9358: if (defined($changed_items{$itemnum})) {
9359: $new_control{$changed_items{$itemnum}} = $now;
9360: push(@deletions,$file_name."\0".$control_item);
9361: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9362: } else {
9363: $new_control{$control_item} = $$curr_controls{$control_item};
9364: }
9365: }
1.745 raeburn 9366: }
9367: }
9368: }
1.970 raeburn 9369: my ($group);
9370: if (&is_course($domain,$user)) {
9371: ($group,my $file) = split(/\//,$file_name,2);
9372: }
1.749 raeburn 9373: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9374: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9375: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9376: # remove lock
9377: my @del_lock = ($file_name."\0".'locked_access_records');
9378: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9379: my $sqlresult =
1.970 raeburn 9380: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9381: $group);
1.749 raeburn 9382: } else {
9383: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9384: }
1.749 raeburn 9385: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9386: }
9387:
1.827 raeburn 9388: sub make_public_indefinitely {
9389: my ($requrl) = @_;
9390: my $now = time;
9391: my $action = 'activate';
9392: my $aclnum = 0;
9393: if (&is_portfolio_url($requrl)) {
9394: my (undef,$udom,$unum,$file_name,$group) =
9395: &parse_portfolio_url($requrl);
9396: my $current_perms = &get_portfile_permissions($udom,$unum);
9397: my %access_controls = &get_access_controls($current_perms,
9398: $group,$file_name);
9399: foreach my $key (keys(%{$access_controls{$file_name}})) {
9400: my ($num,$scope,$end,$start) =
9401: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9402: if ($scope eq 'public') {
9403: if ($start <= $now && $end == 0) {
9404: $action = 'none';
9405: } else {
9406: $action = 'update';
9407: $aclnum = $num;
9408: }
9409: last;
9410: }
9411: }
9412: if ($action eq 'none') {
9413: return 'ok';
9414: } else {
9415: my %changes;
9416: my $newend = 0;
9417: my $newstart = $now;
9418: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9419: $changes{$action}{$newkey} = {
9420: type => 'public',
9421: time => {
9422: start => $newstart,
9423: end => $newend,
9424: },
9425: };
9426: my ($outcome,$deloutcome,$new_values,$translation) =
9427: &modify_access_controls($file_name,\%changes,$udom,$unum);
9428: return $outcome;
9429: }
9430: } else {
9431: return 'invalid';
9432: }
9433: }
9434:
1.745 raeburn 9435: #------------------------------------------------------Get Marked as Read Only
9436:
9437: sub get_marked_as_readonly {
9438: my ($domain,$user,$what,$group) = @_;
9439: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9440: my @readonly_files;
1.629 banghart 9441: my $cmp1=$what;
9442: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9443: while (my ($file_name,$value) = each(%{$current_permissions})) {
9444: if (defined($group)) {
9445: if ($file_name !~ m-^\Q$group\E/-) {
9446: next;
9447: }
9448: }
1.561 banghart 9449: if (ref($value) eq "ARRAY"){
9450: foreach my $stored_what (@{$value}) {
1.629 banghart 9451: my $cmp2=$stored_what;
1.759 albertel 9452: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9453: $cmp2=join('',@{$stored_what});
1.745 raeburn 9454: }
1.629 banghart 9455: if ($cmp1 eq $cmp2) {
1.561 banghart 9456: push(@readonly_files, $file_name);
1.745 raeburn 9457: last;
1.563 banghart 9458: } elsif (!defined($what)) {
9459: push(@readonly_files, $file_name);
1.745 raeburn 9460: last;
1.561 banghart 9461: }
9462: }
1.745 raeburn 9463: }
1.561 banghart 9464: }
9465: return @readonly_files;
9466: }
1.577 banghart 9467: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9468:
1.577 banghart 9469: sub get_marked_as_readonly_hash {
1.745 raeburn 9470: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9471: my %readonly_files;
1.745 raeburn 9472: while (my ($file_name,$value) = each(%{$current_permissions})) {
9473: if (defined($group)) {
9474: if ($file_name !~ m-^\Q$group\E/-) {
9475: next;
9476: }
9477: }
1.577 banghart 9478: if (ref($value) eq "ARRAY"){
9479: foreach my $stored_what (@{$value}) {
1.745 raeburn 9480: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9481: foreach my $lock_descriptor(@{$stored_what}) {
9482: if ($lock_descriptor eq 'graded') {
9483: $readonly_files{$file_name} = 'graded';
9484: } elsif ($lock_descriptor eq 'handback') {
9485: $readonly_files{$file_name} = 'handback';
9486: } else {
9487: if (!exists($readonly_files{$file_name})) {
9488: $readonly_files{$file_name} = 'locked';
9489: }
9490: }
1.745 raeburn 9491: }
1.750 banghart 9492: }
1.577 banghart 9493: }
9494: }
9495: }
9496: return %readonly_files;
9497: }
1.559 banghart 9498: # ------------------------------------------------------------ Unmark as Read Only
9499:
9500: sub unmark_as_readonly {
1.629 banghart 9501: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9502: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9503: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9504: $file_name = &declutter_portfile($file_name);
1.634 albertel 9505: my $symb_crs = $what;
9506: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9507: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9508: my ($tmp)=keys(%current_permissions);
9509: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9510: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9511: foreach my $file (@readonly_files) {
1.759 albertel 9512: my $clean_file = &declutter_portfile($file);
9513: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9514: my $current_locks = $current_permissions{$file};
1.563 banghart 9515: my @new_locks;
9516: my @del_keys;
9517: if (ref($current_locks) eq "ARRAY"){
9518: foreach my $locker (@{$current_locks}) {
1.632 albertel 9519: my $compare=$locker;
1.749 raeburn 9520: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9521: $compare=join('',@{$locker});
1.746 raeburn 9522: if ($compare ne $symb_crs) {
9523: push(@new_locks, $locker);
9524: }
1.563 banghart 9525: }
9526: }
1.650 albertel 9527: if (scalar(@new_locks) > 0) {
1.563 banghart 9528: $current_permissions{$file} = \@new_locks;
9529: } else {
9530: push(@del_keys, $file);
1.613 albertel 9531: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9532: delete($current_permissions{$file});
1.563 banghart 9533: }
9534: }
1.561 banghart 9535: }
1.613 albertel 9536: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9537: return;
9538: }
1.512 banghart 9539:
1.17 www 9540: # ------------------------------------------------------------ Directory lister
9541:
9542: sub dirlist {
1.955 raeburn 9543: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9544: $uri=~s/^\///;
9545: $uri=~s/\/$//;
1.253 stredwic 9546: my ($udom, $uname);
1.955 raeburn 9547: if ($getuserdir) {
1.253 stredwic 9548: $udom = $userdomain;
9549: $uname = $username;
1.955 raeburn 9550: } else {
9551: (undef,$udom,$uname)=split(/\//,$uri);
9552: if(defined($userdomain)) {
9553: $udom = $userdomain;
9554: }
9555: if(defined($username)) {
9556: $uname = $username;
9557: }
1.253 stredwic 9558: }
1.955 raeburn 9559: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9560:
1.955 raeburn 9561: $dirRoot = $perlvar{'lonDocRoot'};
9562: if (defined($getpropath)) {
9563: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9564: $dirRoot =~ s/\/$//;
1.955 raeburn 9565: } elsif (defined($getuserdir)) {
9566: my $subdir=$uname.'__';
9567: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9568: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9569: ."/$udom/$subdir/$uname";
9570: } elsif (defined($alternateRoot)) {
9571: $dirRoot = $alternateRoot;
1.751 banghart 9572: }
1.253 stredwic 9573:
9574: if($udom) {
9575: if($uname) {
1.1135 raeburn 9576: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9577: if ($uhome eq 'no_host') {
9578: return ([],'no_host');
9579: }
1.955 raeburn 9580: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9581: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9582: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9583: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9584: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9585: } else {
9586: @listing_results = map { &unescape($_); } split(/:/,$listing);
9587: }
1.605 matthew 9588: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9589: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9590: @listing_results = split(/:/,$listing);
9591: } else {
9592: @listing_results = map { &unescape($_); } split(/:/,$listing);
9593: }
1.1135 raeburn 9594: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9595: ($listing eq 'rejected') || ($listing eq 'refused') ||
9596: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9597: return ([],$listing);
9598: } else {
9599: return (\@listing_results);
1.1135 raeburn 9600: }
1.955 raeburn 9601: } elsif(!$alternateRoot) {
1.1136 raeburn 9602: my (%allusers,%listerror);
1.841 albertel 9603: my %servers = &get_servers($udom,'library');
1.955 raeburn 9604: foreach my $tryserver (keys(%servers)) {
9605: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9606: &escape($udom),$tryserver);
9607: if ($listing eq 'unknown_cmd') {
9608: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9609: $udom, $tryserver);
9610: } else {
9611: @listing_results = map { &unescape($_); } split(/:/,$listing);
9612: }
1.841 albertel 9613: if ($listing eq 'unknown_cmd') {
9614: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9615: $udom, $tryserver);
9616: @listing_results = split(/:/,$listing);
9617: } else {
9618: @listing_results =
9619: map { &unescape($_); } split(/:/,$listing);
9620: }
1.1136 raeburn 9621: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9622: ($listing eq 'rejected') || ($listing eq 'refused') ||
9623: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9624: $listerror{$tryserver} = $listing;
9625: } else {
1.841 albertel 9626: foreach my $line (@listing_results) {
9627: my ($entry) = split(/&/,$line,2);
9628: $allusers{$entry} = 1;
9629: }
9630: }
1.253 stredwic 9631: }
1.1136 raeburn 9632: my @alluserslist=();
1.800 albertel 9633: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9634: push(@alluserslist,$user.'&user');
1.253 stredwic 9635: }
1.1136 raeburn 9636: return (\@alluserslist);
1.253 stredwic 9637: } else {
1.1136 raeburn 9638: return ([],'missing username');
1.253 stredwic 9639: }
1.955 raeburn 9640: } elsif(!defined($getpropath)) {
1.1136 raeburn 9641: my $path = $perlvar{'lonDocRoot'}.'/res/';
9642: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9643: return (\@all_domains);
1.955 raeburn 9644: } else {
1.1136 raeburn 9645: return ([],'missing domain');
1.275 stredwic 9646: }
9647: }
9648:
9649: # --------------------------------------------- GetFileTimestamp
9650: # This function utilizes dirlist and returns the date stamp for
9651: # when it was last modified. It will also return an error of -1
9652: # if an error occurs
9653:
9654: sub GetFileTimestamp {
1.955 raeburn 9655: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9656: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9657: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9658: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9659: undef,$getuserdir);
9660: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9661: return -1;
9662: }
9663: if (ref($fileref) eq 'ARRAY') {
9664: my @stats = split('&',$fileref->[0]);
1.375 matthew 9665: # @stats contains first the filename, then the stat output
9666: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9667: } else {
9668: return -1;
1.253 stredwic 9669: }
1.26 www 9670: }
9671:
1.712 albertel 9672: sub stat_file {
9673: my ($uri) = @_;
1.787 albertel 9674: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9675:
1.955 raeburn 9676: my ($udom,$uname,$file);
1.712 albertel 9677: if ($uri =~ m-^/(uploaded|editupload)/-) {
9678: ($udom,$uname,$file) =
1.811 albertel 9679: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9680: $file = 'userfiles/'.$file;
9681: }
9682: if ($uri =~ m-^/res/-) {
9683: ($udom,$uname) =
1.807 albertel 9684: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9685: $file = $uri;
9686: }
9687:
9688: if (!$udom || !$uname || !$file) {
9689: # unable to handle the uri
9690: return ();
9691: }
1.956 raeburn 9692: my $getpropath;
9693: if ($file =~ /^userfiles\//) {
9694: $getpropath = 1;
9695: }
1.1136 raeburn 9696: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9697: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9698: return ();
9699: } else {
9700: if (ref($listref) eq 'ARRAY') {
9701: my @stats = split('&',$listref->[0]);
9702: shift(@stats); #filename is first
9703: return @stats;
9704: }
1.712 albertel 9705: }
9706: return ();
9707: }
9708:
1.26 www 9709: # -------------------------------------------------------- Value of a Condition
9710:
1.713 albertel 9711: # gets the value of a specific preevaluated condition
9712: # stored in the string $env{user.state.<cid>}
9713: # or looks up a condition reference in the bighash and if if hasn't
9714: # already been evaluated recurses into docondval to get the value of
9715: # the condition, then memoizing it to
9716: # $env{user.state.<cid>.<condition>}
1.40 www 9717: sub directcondval {
9718: my $number=shift;
1.620 albertel 9719: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9720: &Apache::lonuserstate::evalstate();
9721: }
1.713 albertel 9722: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9723: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9724: } elsif ($number =~ /^_/) {
9725: my $sub_condition;
9726: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9727: &GDBM_READER(),0640)) {
9728: $sub_condition=$bighash{'conditions'.$number};
9729: untie(%bighash);
9730: }
9731: my $value = &docondval($sub_condition);
1.949 raeburn 9732: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9733: return $value;
9734: }
1.620 albertel 9735: if ($env{'user.state.'.$env{'request.course.id'}}) {
9736: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9737: } else {
9738: return 2;
9739: }
9740: }
9741:
1.713 albertel 9742: # get the collection of conditions for this resource
1.26 www 9743: sub condval {
9744: my $condidx=shift;
1.54 www 9745: my $allpathcond='';
1.713 albertel 9746: foreach my $cond (split(/\|/,$condidx)) {
9747: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9748: $allpathcond.=
9749: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9750: }
1.191 harris41 9751: }
1.54 www 9752: $allpathcond=~s/\|$//;
1.713 albertel 9753: return &docondval($allpathcond);
9754: }
9755:
9756: #evaluates an expression of conditions
9757: sub docondval {
9758: my ($allpathcond) = @_;
9759: my $result=0;
9760: if ($env{'request.course.id'}
9761: && defined($allpathcond)) {
9762: my $operand='|';
9763: my @stack;
9764: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9765: if ($chunk eq '(') {
9766: push @stack,($operand,$result);
9767: } elsif ($chunk eq ')') {
9768: my $before=pop @stack;
9769: if (pop @stack eq '&') {
9770: $result=$result>$before?$before:$result;
9771: } else {
9772: $result=$result>$before?$result:$before;
9773: }
9774: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9775: $operand=$chunk;
9776: } else {
9777: my $new=directcondval($chunk);
9778: if ($operand eq '&') {
9779: $result=$result>$new?$new:$result;
9780: } else {
9781: $result=$result>$new?$result:$new;
9782: }
9783: }
9784: }
1.26 www 9785: }
9786: return $result;
1.421 albertel 9787: }
9788:
9789: # ---------------------------------------------------- Devalidate courseresdata
9790:
9791: sub devalidatecourseresdata {
9792: my ($coursenum,$coursedomain)=@_;
9793: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9794: &devalidate_cache_new('courseres',$hashid);
1.28 www 9795: }
9796:
1.763 www 9797:
1.200 www 9798: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9799: #
9800: # Parameters:
9801: # $coursenum - Number of the course.
9802: # $coursedomain - Domain at which the course was created.
9803: # Returns:
9804: # A hash of the course parameters along (I think) with timestamps
9805: # and version info.
1.877 foxr 9806:
1.624 albertel 9807: sub get_courseresdata {
9808: my ($coursenum,$coursedomain)=@_;
1.200 www 9809: my $coursehom=&homeserver($coursenum,$coursedomain);
9810: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9811: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9812: my %dumpreply;
1.417 albertel 9813: unless (defined($cached)) {
1.624 albertel 9814: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9815: $result=\%dumpreply;
1.251 albertel 9816: my ($tmp) = keys(%dumpreply);
9817: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9818: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9819: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9820: return $tmp;
1.416 albertel 9821: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9822: $result=undef;
1.599 albertel 9823: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9824: }
9825: }
1.624 albertel 9826: return $result;
9827: }
9828:
1.633 albertel 9829: sub devalidateuserresdata {
9830: my ($uname,$udom)=@_;
9831: my $hashid="$udom:$uname";
9832: &devalidate_cache_new('userres',$hashid);
9833: }
9834:
1.624 albertel 9835: sub get_userresdata {
9836: my ($uname,$udom)=@_;
9837: #most student don\'t have any data set, check if there is some data
9838: if (&EXT_cache_status($udom,$uname)) { return undef; }
9839:
9840: my $hashid="$udom:$uname";
9841: my ($result,$cached)=&is_cached_new('userres',$hashid);
9842: if (!defined($cached)) {
9843: my %resourcedata=&dump('resourcedata',$udom,$uname);
9844: $result=\%resourcedata;
9845: &do_cache_new('userres',$hashid,$result,600);
9846: }
9847: my ($tmp)=keys(%$result);
9848: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9849: return $result;
9850: }
9851: #error 2 occurs when the .db doesn't exist
9852: if ($tmp!~/error: 2 /) {
1.672 albertel 9853: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9854: " Trying to get resource data for ".
9855: $uname." at ".$udom.": ".
9856: $tmp."</font>");
9857: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9858: #&EXT_cache_set($udom,$uname);
9859: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9860: undef($tmp); # not really an error so don't send it back
1.624 albertel 9861: }
9862: return $tmp;
9863: }
1.879 foxr 9864: #----------------------------------------------- resdata - return resource data
9865: # Purpose:
9866: # Return resource data for either users or for a course.
9867: # Parameters:
9868: # $name - Course/user name.
9869: # $domain - Name of the domain the user/course is registered on.
9870: # $type - Type of thing $name is (must be 'course' or 'user'
9871: # @which - Array of names of resources desired.
9872: # Returns:
9873: # The value of the first reasource in @which that is found in the
9874: # resource hash.
9875: # Exceptional Conditions:
9876: # If the $type passed in is not valid (not the string 'course' or
9877: # 'user', an undefined reference is returned.
9878: # If none of the resources are found, an undef is returned
1.624 albertel 9879: sub resdata {
9880: my ($name,$domain,$type,@which)=@_;
9881: my $result;
9882: if ($type eq 'course') {
9883: $result=&get_courseresdata($name,$domain);
9884: } elsif ($type eq 'user') {
9885: $result=&get_userresdata($name,$domain);
9886: }
9887: if (!ref($result)) { return $result; }
1.251 albertel 9888: foreach my $item (@which) {
1.927 albertel 9889: if (defined($result->{$item->[0]})) {
9890: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9891: }
1.250 albertel 9892: }
1.291 albertel 9893: return undef;
1.200 www 9894: }
9895:
1.1172.2.31 raeburn 9896: sub get_numsuppfiles {
9897: my ($cnum,$cdom,$ignorecache)=@_;
9898: my $hashid=$cnum.':'.$cdom;
9899: my ($suppcount,$cached);
9900: unless ($ignorecache) {
9901: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9902: }
9903: unless (defined($cached)) {
9904: my $chome=&homeserver($cnum,$cdom);
9905: unless ($chome eq 'no_host') {
9906: ($suppcount,my $errors) = (0,0);
9907: my $suppmap = 'supplemental.sequence';
9908: ($suppcount,$errors) =
9909: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9910: }
9911: &do_cache_new('suppcount',$hashid,$suppcount,600);
9912: }
9913: return $suppcount;
9914: }
9915:
1.379 matthew 9916: #
9917: # EXT resource caching routines
9918: #
9919:
9920: sub clear_EXT_cache_status {
1.383 albertel 9921: &delenv('cache.EXT.');
1.379 matthew 9922: }
9923:
9924: sub EXT_cache_status {
9925: my ($target_domain,$target_user) = @_;
1.383 albertel 9926: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9927: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9928: # We know already the user has no data
9929: return 1;
9930: } else {
9931: return 0;
9932: }
9933: }
9934:
9935: sub EXT_cache_set {
9936: my ($target_domain,$target_user) = @_;
1.383 albertel 9937: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9938: #&appenv({$cachename => time});
1.379 matthew 9939: }
9940:
1.28 www 9941: # --------------------------------------------------------- Value of a Variable
1.58 www 9942: sub EXT {
1.715 albertel 9943:
1.1172.2.28 raeburn 9944: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9945: unless ($varname) { return ''; }
1.218 albertel 9946: #get real user name/domain, courseid and symb
9947: my $courseid;
1.359 albertel 9948: my $publicuser;
1.427 www 9949: if ($symbparm) {
9950: $symbparm=&get_symb_from_alias($symbparm);
9951: }
1.218 albertel 9952: if (!($uname && $udom)) {
1.790 albertel 9953: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9954: if (!$symbparm) { $symbparm=$cursymb; }
9955: } else {
1.620 albertel 9956: $courseid=$env{'request.course.id'};
1.218 albertel 9957: }
1.48 www 9958: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9959: my $rest;
1.320 albertel 9960: if (defined($therest[0])) {
1.48 www 9961: $rest=join('.',@therest);
9962: } else {
9963: $rest='';
9964: }
1.320 albertel 9965:
1.57 www 9966: my $qualifierrest=$qualifier;
9967: if ($rest) { $qualifierrest.='.'.$rest; }
9968: my $spacequalifierrest=$space;
9969: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9970: if ($realm eq 'user') {
1.48 www 9971: # --------------------------------------------------------------- user.resource
9972: if ($space eq 'resource') {
1.651 albertel 9973: if ( (defined($Apache::lonhomework::parsing_a_problem)
9974: || defined($Apache::lonhomework::parsing_a_task))
9975: &&
1.744 albertel 9976: ($symbparm eq &symbread()) ) {
9977: # if we are in the middle of processing the resource the
9978: # get the value we are planning on committing
9979: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9980: return $Apache::lonhomework::results{$qualifierrest};
9981: } else {
9982: return $Apache::lonhomework::history{$qualifierrest};
9983: }
1.335 albertel 9984: } else {
1.359 albertel 9985: my %restored;
1.620 albertel 9986: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9987: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9988: } else {
9989: %restored=&restore($symbparm,$courseid,$udom,$uname);
9990: }
1.335 albertel 9991: return $restored{$qualifierrest};
9992: }
1.48 www 9993: # ----------------------------------------------------------------- user.access
9994: } elsif ($space eq 'access') {
1.218 albertel 9995: # FIXME - not supporting calls for a specific user
1.48 www 9996: return &allowed($qualifier,$rest);
9997: # ------------------------------------------ user.preferences, user.environment
9998: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9999: if (($uname eq $env{'user.name'}) &&
10000: ($udom eq $env{'user.domain'})) {
10001: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10002: } else {
1.359 albertel 10003: my %returnhash;
10004: if (!$publicuser) {
10005: %returnhash=&userenvironment($udom,$uname,
10006: $qualifierrest);
10007: }
1.218 albertel 10008: return $returnhash{$qualifierrest};
10009: }
1.48 www 10010: # ----------------------------------------------------------------- user.course
10011: } elsif ($space eq 'course') {
1.218 albertel 10012: # FIXME - not supporting calls for a specific user
1.620 albertel 10013: return $env{join('.',('request.course',$qualifier))};
1.48 www 10014: # ------------------------------------------------------------------- user.role
10015: } elsif ($space eq 'role') {
1.218 albertel 10016: # FIXME - not supporting calls for a specific user
1.620 albertel 10017: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10018: if ($qualifier eq 'value') {
10019: return $role;
10020: } elsif ($qualifier eq 'extent') {
10021: return $where;
10022: }
10023: # ----------------------------------------------------------------- user.domain
10024: } elsif ($space eq 'domain') {
1.218 albertel 10025: return $udom;
1.48 www 10026: # ------------------------------------------------------------------- user.name
10027: } elsif ($space eq 'name') {
1.218 albertel 10028: return $uname;
1.48 www 10029: # ---------------------------------------------------- Any other user namespace
1.29 www 10030: } else {
1.359 albertel 10031: my %reply;
10032: if (!$publicuser) {
10033: %reply=&get($space,[$qualifierrest],$udom,$uname);
10034: }
10035: return $reply{$qualifierrest};
1.48 www 10036: }
1.236 www 10037: } elsif ($realm eq 'query') {
10038: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10039: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10040: [$spacequalifierrest]);
1.620 albertel 10041: return $env{'form.'.$spacequalifierrest};
1.236 www 10042: } elsif ($realm eq 'request') {
1.48 www 10043: # ------------------------------------------------------------- request.browser
10044: if ($space eq 'browser') {
1.1145 bisitz 10045: return $env{'browser.'.$qualifier};
1.57 www 10046: # ------------------------------------------------------------ request.filename
10047: } else {
1.620 albertel 10048: return $env{'request.'.$spacequalifierrest};
1.29 www 10049: }
1.28 www 10050: } elsif ($realm eq 'course') {
1.48 www 10051: # ---------------------------------------------------------- course.description
1.620 albertel 10052: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10053: } elsif ($realm eq 'resource') {
1.165 www 10054:
1.620 albertel 10055: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10056: if (!$symbparm) { $symbparm=&symbread(); }
10057: }
1.693 albertel 10058:
1.1172.2.30 raeburn 10059: if ($qualifier eq '') {
10060: if ($space eq 'title') {
10061: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10062: return &gettitle($symbparm);
10063: }
1.693 albertel 10064:
1.1172.2.30 raeburn 10065: if ($space eq 'map') {
10066: my ($map) = &decode_symb($symbparm);
10067: return &symbread($map);
10068: }
10069: if ($space eq 'maptitle') {
10070: my ($map) = &decode_symb($symbparm);
10071: return &gettitle($map);
10072: }
10073: if ($space eq 'filename') {
10074: if ($symbparm) {
10075: return &clutter((&decode_symb($symbparm))[2]);
10076: }
10077: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10078: }
1.1172.2.30 raeburn 10079:
10080: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10081: if ($space eq 'visibleparts') {
10082: my $navmap = Apache::lonnavmaps::navmap->new();
10083: my $item;
10084: if (ref($navmap)) {
10085: my $res = $navmap->getBySymb($symbparm);
10086: my $parts = $res->parts();
10087: if (ref($parts) eq 'ARRAY') {
10088: $item = join(',',@{$parts});
10089: }
10090: undef($navmap);
10091: }
10092: return $item;
10093: }
10094: }
10095: }
1.693 albertel 10096:
10097: my ($section, $group, @groups);
1.593 albertel 10098: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10099: if (($courseid eq '') && ($cid)) {
10100: $courseid = $cid;
10101: }
10102: if (($symbparm && $courseid) &&
10103: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10104:
1.218 albertel 10105: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10106:
1.60 www 10107: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10108: my $symbp=$symbparm;
1.735 albertel 10109: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10110:
10111: my $symbparm=$symbp.'.'.$spacequalifierrest;
10112: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10113:
1.620 albertel 10114: if (($env{'user.name'} eq $uname) &&
10115: ($env{'user.domain'} eq $udom)) {
10116: $section=$env{'request.course.sec'};
1.733 raeburn 10117: @groups = split(/:/,$env{'request.course.groups'});
10118: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10119: } else {
1.539 albertel 10120: if (! defined($usection)) {
1.551 albertel 10121: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10122: } else {
10123: $section = $usection;
10124: }
1.733 raeburn 10125: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10126: }
10127:
10128: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10129: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10130: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10131:
1.593 albertel 10132: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10133: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10134: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10135:
1.60 www 10136: # ----------------------------------------------------------- first, check user
1.624 albertel 10137:
10138: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10139: ([$courselevelr,'resource'],
10140: [$courselevelm,'map' ],
10141: [$courselevel, 'course' ]));
1.931 albertel 10142: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10143:
1.594 albertel 10144: # ------------------------------------------------ second, check some of course
1.684 raeburn 10145: my $coursereply;
1.691 raeburn 10146: if (@groups > 0) {
10147: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10148: $mapparm,$spacequalifierrest);
1.927 albertel 10149: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10150: }
1.96 www 10151:
1.684 raeburn 10152: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10153: $env{'course.'.$courseid.'.domain'},
10154: 'course',
10155: ([$seclevelr, 'resource'],
10156: [$seclevelm, 'map' ],
10157: [$seclevel, 'course' ],
10158: [$courselevelr,'resource']));
10159: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10160:
1.60 www 10161: # ------------------------------------------------------ third, check map parms
1.218 albertel 10162: my %parmhash=();
10163: my $thisparm='';
10164: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10165: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10166: &GDBM_READER(),0640)) {
1.218 albertel 10167: $thisparm=$parmhash{$symbparm};
10168: untie(%parmhash);
10169: }
1.927 albertel 10170: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10171: }
1.594 albertel 10172: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10173:
1.218 albertel 10174: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10175: my $filename;
10176: if (!$symbparm) { $symbparm=&symbread(); }
10177: if ($symbparm) {
1.409 www 10178: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10179: } else {
1.620 albertel 10180: $filename=$env{'request.filename'};
1.282 albertel 10181: }
10182: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10183: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10184: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10185: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10186:
1.927 albertel 10187: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10188: if ($symbparm && defined($courseid) &&
1.620 albertel 10189: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10190: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10191: $env{'course.'.$courseid.'.domain'},
10192: 'course',
1.927 albertel 10193: ([$courselevelm,'map' ],
10194: [$courselevel, 'course']));
10195: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10196: }
1.145 www 10197: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10198: unless ($space eq '0') {
1.336 albertel 10199: my @parts=split(/_/,$space);
10200: my $id=pop(@parts);
10201: my $part=join('_',@parts);
10202: if ($part eq '') { $part='0'; }
1.927 albertel 10203: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10204: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10205: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10206: }
1.395 albertel 10207: if ($recurse) { return undef; }
10208: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10209: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10210: # ---------------------------------------------------- Any other user namespace
10211: } elsif ($realm eq 'environment') {
10212: # ----------------------------------------------------------------- environment
1.620 albertel 10213: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10214: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10215: } else {
1.770 albertel 10216: if ($uname eq 'anonymous' && $udom eq '') {
10217: return '';
10218: }
1.219 albertel 10219: my %returnhash=&userenvironment($udom,$uname,
10220: $spacequalifierrest);
10221: return $returnhash{$spacequalifierrest};
10222: }
1.28 www 10223: } elsif ($realm eq 'system') {
1.48 www 10224: # ----------------------------------------------------------------- system.time
10225: if ($space eq 'time') {
10226: return time;
10227: }
1.696 albertel 10228: } elsif ($realm eq 'server') {
10229: # ----------------------------------------------------------------- system.time
10230: if ($space eq 'name') {
10231: return $ENV{'SERVER_NAME'};
10232: }
1.28 www 10233: }
1.48 www 10234: return '';
1.61 www 10235: }
10236:
1.927 albertel 10237: sub get_reply {
10238: my ($reply_value) = @_;
1.940 raeburn 10239: if (ref($reply_value) eq 'ARRAY') {
10240: if (wantarray) {
10241: return @$reply_value;
10242: }
10243: return $reply_value->[0];
10244: } else {
10245: return $reply_value;
1.927 albertel 10246: }
10247: }
10248:
1.691 raeburn 10249: sub check_group_parms {
10250: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10251: my @groupitems = ();
10252: my $resultitem;
1.927 albertel 10253: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10254: foreach my $group (@{$groups}) {
10255: foreach my $level (@levels) {
1.927 albertel 10256: my $item = $courseid.'.['.$group.'].'.$level->[0];
10257: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10258: }
10259: }
10260: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10261: $env{'course.'.$courseid.'.domain'},
10262: 'course',@groupitems);
10263: return $coursereply;
10264: }
10265:
10266: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10267: my ($courseid,@groups) = @_;
10268: @groups = sort(@groups);
1.691 raeburn 10269: return @groups;
10270: }
10271:
1.395 albertel 10272: sub packages_tab_default {
10273: my ($uri,$varname)=@_;
10274: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10275:
10276: my (@extension,@specifics,$do_default);
10277: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10278: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10279: if ($pack_type eq 'default') {
10280: $do_default=1;
10281: } elsif ($pack_type eq 'extension') {
10282: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10283: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10284: # only look at packages defaults for packages that this id is
1.738 albertel 10285: push(@specifics,[$package,$pack_type,$pack_part]);
10286: }
10287: }
10288: # first look for a package that matches the requested part id
10289: foreach my $package (@specifics) {
10290: my (undef,$pack_type,$pack_part)=@{$package};
10291: next if ($pack_part ne $part);
10292: if (defined($packagetab{"$pack_type&$name&default"})) {
10293: return $packagetab{"$pack_type&$name&default"};
10294: }
10295: }
10296: # look for any possible matching non extension_ package
10297: foreach my $package (@specifics) {
10298: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10299: if (defined($packagetab{"$pack_type&$name&default"})) {
10300: return $packagetab{"$pack_type&$name&default"};
10301: }
1.585 albertel 10302: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10303: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10304: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10305: }
10306: }
1.738 albertel 10307: # look for any posible extension_ match
10308: foreach my $package (@extension) {
10309: my ($package,$pack_type)=@{$package};
10310: if (defined($packagetab{"$pack_type&$name&default"})) {
10311: return $packagetab{"$pack_type&$name&default"};
10312: }
10313: if (defined($packagetab{$package."&$name&default"})) {
10314: return $packagetab{$package."&$name&default"};
10315: }
10316: }
10317: # look for a global default setting
10318: if ($do_default && defined($packagetab{"default&$name&default"})) {
10319: return $packagetab{"default&$name&default"};
10320: }
1.395 albertel 10321: return undef;
10322: }
10323:
1.334 albertel 10324: sub add_prefix_and_part {
10325: my ($prefix,$part)=@_;
10326: my $keyroot;
10327: if (defined($prefix) && $prefix !~ /^__/) {
10328: # prefix that has a part already
10329: $keyroot=$prefix;
10330: } elsif (defined($prefix)) {
10331: # prefix that is missing a part
10332: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10333: } else {
10334: # no prefix at all
10335: if (defined($part)) { $keyroot='_'.$part; }
10336: }
10337: return $keyroot;
10338: }
10339:
1.71 www 10340: # ---------------------------------------------------------------- Get metadata
10341:
1.599 albertel 10342: my %metaentry;
1.1070 www 10343: my %importedpartids;
1.71 www 10344: sub metadata {
1.176 www 10345: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10346: $uri=&declutter($uri);
1.288 albertel 10347: # if it is a non metadata possible uri return quickly
1.529 albertel 10348: if (($uri eq '') ||
10349: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10350: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10351: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10352: return undef;
10353: }
1.1172.2.49 raeburn 10354: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10355: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10356: return undef;
1.288 albertel 10357: }
1.73 www 10358: my $filename=$uri;
10359: $uri=~s/\.meta$//;
1.172 www 10360: #
10361: # Is the metadata already cached?
1.177 www 10362: # Look at timestamp of caching
1.172 www 10363: # Everything is cached by the main uri, libraries are never directly cached
10364: #
1.428 albertel 10365: if (!defined($liburi)) {
1.599 albertel 10366: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10367: if (defined($cached)) { return $result->{':'.$what}; }
10368: }
10369: {
1.1069 www 10370: # Imported parts would go here
1.1070 www 10371: my %importedids=();
10372: my @origfileimportpartids=();
1.1069 www 10373: my $importedparts=0;
1.172 www 10374: #
10375: # Is this a recursive call for a library?
10376: #
1.599 albertel 10377: # if (! exists($metacache{$uri})) {
10378: # $metacache{$uri}={};
10379: # }
1.924 albertel 10380: my $cachetime = 60*60;
1.171 www 10381: if ($liburi) {
10382: $liburi=&declutter($liburi);
10383: $filename=$liburi;
1.401 bowersj2 10384: } else {
1.599 albertel 10385: &devalidate_cache_new('meta',$uri);
10386: undef(%metaentry);
1.401 bowersj2 10387: }
1.140 www 10388: my %metathesekeys=();
1.73 www 10389: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10390: my $metastring;
1.1140 www 10391: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10392: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10393: $metastring =
1.929 albertel 10394: &Apache::lonnet::ssi_body($which,
1.924 albertel 10395: ('grade_target' => 'meta'));
10396: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10397: } elsif (($uri !~ m -^(editupload)/-) &&
10398: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10399: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10400: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10401: $metastring=&getfile($file);
1.489 albertel 10402: }
1.208 albertel 10403: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10404: my $token;
1.140 www 10405: undef %metathesekeys;
1.71 www 10406: while ($token=$parser->get_token) {
1.339 albertel 10407: if ($token->[0] eq 'S') {
10408: if (defined($token->[2]->{'package'})) {
1.172 www 10409: #
10410: # This is a package - get package info
10411: #
1.339 albertel 10412: my $package=$token->[2]->{'package'};
10413: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10414: if (defined($token->[2]->{'id'})) {
10415: $keyroot.='_'.$token->[2]->{'id'};
10416: }
1.599 albertel 10417: if ($metaentry{':packages'}) {
10418: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10419: } else {
1.599 albertel 10420: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10421: }
1.736 albertel 10422: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10423: my $part=$keyroot;
10424: $part=~s/^\_//;
1.736 albertel 10425: if ($pack_entry=~/^\Q$package\E\&/ ||
10426: $pack_entry=~/^\Q$package\E_0\&/) {
10427: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10428: # ignore package.tab specified default values
10429: # here &package_tab_default() will fetch those
10430: if ($subp eq 'default') { next; }
1.736 albertel 10431: my $value=$packagetab{$pack_entry};
1.432 albertel 10432: my $unikey;
10433: if ($pack =~ /_0$/) {
10434: $unikey='parameter_0_'.$name;
10435: $part=0;
10436: } else {
10437: $unikey='parameter'.$keyroot.'_'.$name;
10438: }
1.339 albertel 10439: if ($subp eq 'display') {
10440: $value.=' [Part: '.$part.']';
10441: }
1.599 albertel 10442: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10443: $metathesekeys{$unikey}=1;
1.599 albertel 10444: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10445: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10446: }
1.599 albertel 10447: if (defined($metaentry{':'.$unikey.'.default'})) {
10448: $metaentry{':'.$unikey}=
10449: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10450: }
1.339 albertel 10451: }
10452: }
10453: } else {
1.172 www 10454: #
10455: # This is not a package - some other kind of start tag
1.339 albertel 10456: #
10457: my $entry=$token->[1];
1.1068 www 10458: my $unikey='';
1.175 www 10459:
1.339 albertel 10460: if ($entry eq 'import') {
1.175 www 10461: #
10462: # Importing a library here
1.339 albertel 10463: #
1.1067 www 10464: my $location=$parser->get_text('/import');
10465: my $dir=$filename;
10466: $dir=~s|[^/]*$||;
10467: $location=&filelocation($dir,$location);
1.1069 www 10468:
1.1068 www 10469: my $importmode=$token->[2]->{'importmode'};
10470: if ($importmode eq 'problem') {
1.1069 www 10471: # Import as problem/response
1.1068 www 10472: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10473: } elsif ($importmode eq 'part') {
10474: # Import as part(s)
1.1069 www 10475: $importedparts=1;
10476: # We need to get the original file and the imported file to get the part order correct
10477: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10478: # Load and inspect original file
1.1070 www 10479: if ($#origfileimportpartids<0) {
10480: undef(%importedpartids);
10481: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10482: my $origfile=&getfile($origfilelocation);
10483: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10484: }
10485:
1.1069 www 10486: # Load and inspect imported file
10487: my $impfile=&getfile($location);
10488: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10489: if ($#impfilepartids>=0) {
10490: # This problem had parts
1.1070 www 10491: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10492: } else {
10493: # Importing by turning a single problem into a problem part
10494: # It gets the import-tags ID as part-ID
10495: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10496: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10497: }
1.1068 www 10498: } else {
10499: # Normal import
10500: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10501: if (defined($token->[2]->{'id'})) {
10502: $unikey.='_'.$token->[2]->{'id'};
10503: }
1.1067 www 10504: }
10505:
1.339 albertel 10506: if ($depthcount<20) {
1.736 albertel 10507: my $metadata =
10508: &metadata($uri,'keys', $location,$unikey,
10509: $depthcount+1);
10510: foreach my $meta (split(',',$metadata)) {
10511: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10512: $metathesekeys{$meta}=1;
1.339 albertel 10513: }
1.1068 www 10514:
10515: }
1.1067 www 10516: } else {
10517: #
10518: # Not importing, some other kind of non-package, non-library start tag
10519: #
10520: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10521: if (defined($token->[2]->{'id'})) {
10522: $unikey.='_'.$token->[2]->{'id'};
10523: }
1.339 albertel 10524: if (defined($token->[2]->{'name'})) {
10525: $unikey.='_'.$token->[2]->{'name'};
10526: }
10527: $metathesekeys{$unikey}=1;
1.736 albertel 10528: foreach my $param (@{$token->[3]}) {
10529: $metaentry{':'.$unikey.'.'.$param} =
10530: $token->[2]->{$param};
1.339 albertel 10531: }
10532: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10533: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10534: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10535: # only ws inside the tag, and not in default, so use default
10536: # as value
1.599 albertel 10537: $metaentry{':'.$unikey}=$default;
1.908 albertel 10538: } elsif ( $internaltext =~ /\S/ ) {
10539: # something interesting inside the tag
10540: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10541: } else {
1.908 albertel 10542: # no interesting values, don't set a default
1.339 albertel 10543: }
1.172 www 10544: # end of not-a-package not-a-library import
1.339 albertel 10545: }
1.172 www 10546: # end of not-a-package start tag
1.339 albertel 10547: }
1.172 www 10548: # the next is the end of "start tag"
1.339 albertel 10549: }
10550: }
1.483 albertel 10551: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10552: $extension = lc($extension);
10553: if ($extension eq 'htm') { $extension='html'; }
10554:
1.737 albertel 10555: foreach my $key (keys(%packagetab)) {
1.483 albertel 10556: #no specific packages #how's our extension
10557: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10558: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10559: \%metathesekeys);
10560: }
1.883 albertel 10561:
10562: if (!exists($metaentry{':packages'})
10563: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10564: foreach my $key (keys(%packagetab)) {
1.483 albertel 10565: #no specific packages well let's get default then
10566: if ($key!~/^default&/) { next; }
1.488 albertel 10567: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10568: \%metathesekeys);
10569: }
10570: }
1.338 www 10571: # are there custom rights to evaluate
1.599 albertel 10572: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10573:
1.338 www 10574: #
10575: # Importing a rights file here
1.339 albertel 10576: #
10577: unless ($depthcount) {
1.599 albertel 10578: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10579: my $dir=$filename;
10580: $dir=~s|[^/]*$||;
10581: $location=&filelocation($dir,$location);
1.736 albertel 10582: my $rights_metadata =
10583: &metadata($uri,'keys',$location,'_rights',
10584: $depthcount+1);
10585: foreach my $rights (split(',',$rights_metadata)) {
10586: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10587: $metathesekeys{$rights}=1;
1.339 albertel 10588: }
10589: }
10590: }
1.737 albertel 10591: # uniqifiy package listing
10592: my %seen;
10593: my @uniq_packages =
10594: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10595: $metaentry{':packages'} = join(',',@uniq_packages);
10596:
1.1070 www 10597: if ($importedparts) {
10598: # We had imported parts and need to rebuild partorder
10599: $metaentry{':partorder'}='';
10600: $metathesekeys{'partorder'}=1;
10601: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10602: if ($origfileimportpartids[$index] eq 'part') {
10603: # original part, part of the problem
10604: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10605: } else {
10606: # we have imported parts at this position
10607: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10608: }
10609: }
10610: $metaentry{':partorder'}=~s/^\,//;
10611: }
10612:
1.737 albertel 10613: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10614: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10615: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10616: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10617: # this is the end of "was not already recently cached
1.71 www 10618: }
1.599 albertel 10619: return $metaentry{':'.$what};
1.261 albertel 10620: }
10621:
1.488 albertel 10622: sub metadata_create_package_def {
1.483 albertel 10623: my ($uri,$key,$package,$metathesekeys)=@_;
10624: my ($pack,$name,$subp)=split(/\&/,$key);
10625: if ($subp eq 'default') { next; }
10626:
1.599 albertel 10627: if (defined($metaentry{':packages'})) {
10628: $metaentry{':packages'}.=','.$package;
1.483 albertel 10629: } else {
1.599 albertel 10630: $metaentry{':packages'}=$package;
1.483 albertel 10631: }
10632: my $value=$packagetab{$key};
10633: my $unikey;
10634: $unikey='parameter_0_'.$name;
1.599 albertel 10635: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10636: $$metathesekeys{$unikey}=1;
1.599 albertel 10637: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10638: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10639: }
1.599 albertel 10640: if (defined($metaentry{':'.$unikey.'.default'})) {
10641: $metaentry{':'.$unikey}=
10642: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10643: }
10644: }
10645:
1.261 albertel 10646: sub metadata_generate_part0 {
10647: my ($metadata,$metacache,$uri) = @_;
10648: my %allnames;
1.737 albertel 10649: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10650: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10651: my $part=$$metacache{':'.$metakey.'.part'};
10652: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10653: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10654: $allnames{$name}=$part;
10655: }
10656: }
10657: }
10658: foreach my $name (keys(%allnames)) {
10659: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10660: my $key=":parameter_0_$name";
1.261 albertel 10661: $$metacache{"$key.part"}='0';
10662: $$metacache{"$key.name"}=$name;
1.428 albertel 10663: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10664: $allnames{$name}.'_'.$name.
10665: '.type'};
1.428 albertel 10666: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10667: '.display'};
1.644 www 10668: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10669: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10670: $$metacache{"$key.display"}=$olddis;
10671: }
1.71 www 10672: }
10673:
1.764 albertel 10674: # ------------------------------------------------------ Devalidate title cache
10675:
10676: sub devalidate_title_cache {
10677: my ($url)=@_;
10678: if (!$env{'request.course.id'}) { return; }
10679: my $symb=&symbread($url);
10680: if (!$symb) { return; }
10681: my $key=$env{'request.course.id'}."\0".$symb;
10682: &devalidate_cache_new('title',$key);
10683: }
10684:
1.1014 droeschl 10685: # ------------------------------------------------- Get the title of a course
10686:
10687: sub current_course_title {
10688: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10689: }
1.301 www 10690: # ------------------------------------------------- Get the title of a resource
10691:
10692: sub gettitle {
10693: my $urlsymb=shift;
10694: my $symb=&symbread($urlsymb);
1.534 albertel 10695: if ($symb) {
1.620 albertel 10696: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10697: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10698: if (defined($cached)) {
10699: return $result;
10700: }
1.534 albertel 10701: my ($map,$resid,$url)=&decode_symb($symb);
10702: my $title='';
1.907 albertel 10703: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10704: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10705: } else {
10706: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10707: &GDBM_READER(),0640)) {
10708: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10709: $title=$bighash{'title_'.$mapid.'.'.$resid};
10710: untie(%bighash);
10711: }
1.534 albertel 10712: }
10713: $title=~s/\&colon\;/\:/gs;
10714: if ($title) {
1.1159 www 10715: # Remember both $symb and $title for dynamic metadata
10716: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10717: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10718: # Cache this title and then return it
1.599 albertel 10719: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10720: }
10721: $urlsymb=$url;
10722: }
10723: my $title=&metadata($urlsymb,'title');
10724: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10725: return $title;
1.301 www 10726: }
1.613 albertel 10727:
1.614 albertel 10728: sub get_slot {
10729: my ($which,$cnum,$cdom)=@_;
10730: if (!$cnum || !$cdom) {
1.790 albertel 10731: (undef,my $courseid)=&whichuser();
1.620 albertel 10732: $cdom=$env{'course.'.$courseid.'.domain'};
10733: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10734: }
1.703 albertel 10735: my $key=join("\0",'slots',$cdom,$cnum,$which);
10736: my %slotinfo;
10737: if (exists($remembered{$key})) {
10738: $slotinfo{$which} = $remembered{$key};
10739: } else {
10740: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10741: &Apache::lonhomework::showhash(%slotinfo);
10742: my ($tmp)=keys(%slotinfo);
10743: if ($tmp=~/^error:/) { return (); }
10744: $remembered{$key} = $slotinfo{$which};
10745: }
1.616 albertel 10746: if (ref($slotinfo{$which}) eq 'HASH') {
10747: return %{$slotinfo{$which}};
10748: }
10749: return $slotinfo{$which};
1.614 albertel 10750: }
1.1150 raeburn 10751:
10752: sub get_reservable_slots {
10753: my ($cnum,$cdom,$uname,$udom) = @_;
10754: my $now = time;
10755: my $reservable_info;
10756: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10757: if (exists($remembered{$key})) {
10758: $reservable_info = $remembered{$key};
10759: } else {
10760: my %resv;
10761: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10762: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10763: $reservable_info = \%resv;
10764: $remembered{$key} = $reservable_info;
10765: }
10766: return $reservable_info;
10767: }
10768:
10769: sub get_course_slots {
10770: my ($cnum,$cdom) = @_;
10771: my $hashid=$cnum.':'.$cdom;
10772: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10773: if (defined($cached)) {
10774: if (ref($result) eq 'HASH') {
10775: return %{$result};
10776: }
10777: } else {
10778: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10779: my ($tmp) = keys(%slots);
10780: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10781: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10782: return %slots;
10783: }
10784: }
10785: return;
10786: }
10787:
10788: sub devalidate_slots_cache {
10789: my ($cnum,$cdom)=@_;
10790: my $hashid=$cnum.':'.$cdom;
10791: &devalidate_cache_new('allslots',$hashid);
10792: }
10793:
1.1172.2.8 raeburn 10794: sub get_coursechange {
10795: my ($cdom,$cnum) = @_;
10796: if ($cdom eq '' || $cnum eq '') {
10797: return unless ($env{'request.course.id'});
10798: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10799: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10800: }
10801: my $hashid=$cdom.'_'.$cnum;
10802: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10803: if ((defined($cached)) && ($change ne '')) {
10804: return $change;
10805: } else {
10806: my %crshash;
10807: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10808: if ($crshash{'internal.contentchange'} eq '') {
10809: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10810: if ($change eq '') {
10811: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10812: $change = $crshash{'internal.created'};
10813: }
10814: } else {
10815: $change = $crshash{'internal.contentchange'};
10816: }
10817: my $cachetime = 600;
10818: &do_cache_new('crschange',$hashid,$change,$cachetime);
10819: }
10820: return $change;
10821: }
10822:
10823: sub devalidate_coursechange_cache {
10824: my ($cnum,$cdom)=@_;
10825: my $hashid=$cnum.':'.$cdom;
10826: &devalidate_cache_new('crschange',$hashid);
10827: }
10828:
1.31 www 10829: # ------------------------------------------------- Update symbolic store links
10830:
10831: sub symblist {
10832: my ($mapname,%newhash)=@_;
1.438 www 10833: $mapname=&deversion(&declutter($mapname));
1.31 www 10834: my %hash;
1.620 albertel 10835: if (($env{'request.course.fn'}) && (%newhash)) {
10836: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10837: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10838: foreach my $url (keys(%newhash)) {
1.711 albertel 10839: next if ($url eq 'last_known'
10840: && $env{'form.no_update_last_known'});
10841: $hash{declutter($url)}=&encode_symb($mapname,
10842: $newhash{$url}->[1],
10843: $newhash{$url}->[0]);
1.191 harris41 10844: }
1.31 www 10845: if (untie(%hash)) {
10846: return 'ok';
10847: }
10848: }
10849: }
10850: return 'error';
1.212 www 10851: }
10852:
10853: # --------------------------------------------------------------- Verify a symb
10854:
10855: sub symbverify {
1.1172.2.11 raeburn 10856: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10857: my $thisfn=$thisurl;
1.439 www 10858: $thisfn=&declutter($thisfn);
1.215 www 10859: # direct jump to resource in page or to a sequence - will construct own symbs
10860: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10861: # check URL part
1.409 www 10862: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10863:
1.431 www 10864: unless ($url eq $thisfn) { return 0; }
1.213 www 10865:
1.216 www 10866: $symb=&symbclean($symb);
1.510 www 10867: $thisurl=&deversion($thisurl);
1.439 www 10868: $thisfn=&deversion($thisfn);
1.213 www 10869:
10870: my %bighash;
10871: my $okay=0;
1.431 www 10872:
1.620 albertel 10873: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10874: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10875: my $noclutter;
1.1032 raeburn 10876: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10877: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10878: if ($map =~ m{^uploaded/.+\.page$}) {
10879: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10880: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10881: $noclutter = 1;
10882: }
10883: }
10884: my $ids;
10885: if ($noclutter) {
10886: $ids=$bighash{'ids_'.$thisurl};
10887: } else {
10888: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10889: }
1.1102 raeburn 10890: unless ($ids) {
1.1172.2.13 raeburn 10891: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10892: $ids=$bighash{$idkey};
1.216 www 10893: }
10894: if ($ids) {
10895: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10896: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10897: $symb =~ s/\?.+$//;
10898: }
1.800 albertel 10899: foreach my $id (split(/\,/,$ids)) {
10900: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10901: if (
10902: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10903: eq $symb) {
1.1172.2.11 raeburn 10904: if (ref($encstate)) {
10905: $$encstate = $bighash{'encrypted_'.$id};
10906: }
1.1172.2.13 raeburn 10907: if (($env{'request.role.adv'}) ||
10908: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10909: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10910: $okay=1;
10911: last;
10912: }
10913: }
10914: }
1.216 www 10915: }
1.213 www 10916: untie(%bighash);
10917: }
10918: return $okay;
1.31 www 10919: }
10920:
1.210 www 10921: # --------------------------------------------------------------- Clean-up symb
10922:
10923: sub symbclean {
10924: my $symb=shift;
1.568 albertel 10925: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10926: # remove version from map
10927: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10928:
1.210 www 10929: # remove version from URL
10930: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10931:
1.507 www 10932: # remove wrapper
10933:
1.510 www 10934: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10935: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10936: return $symb;
1.409 www 10937: }
10938:
10939: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10940:
10941: sub encode_symb {
10942: my ($map,$resid,$url)=@_;
10943: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10944: }
1.409 www 10945:
10946: sub decode_symb {
1.568 albertel 10947: my $symb=shift;
10948: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10949: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10950: return (&fixversion($map),$resid,&fixversion($url));
10951: }
10952:
10953: sub fixversion {
10954: my $fn=shift;
1.609 banghart 10955: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10956: my %bighash;
10957: my $uri=&clutter($fn);
1.620 albertel 10958: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10959: # is this cached?
1.599 albertel 10960: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10961: if (defined($cached)) { return $result; }
10962: # unfortunately not cached, or expired
1.620 albertel 10963: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10964: &GDBM_READER(),0640)) {
10965: if ($bighash{'version_'.$uri}) {
10966: my $version=$bighash{'version_'.$uri};
1.444 www 10967: unless (($version eq 'mostrecent') ||
10968: ($version==&getversion($uri))) {
1.440 www 10969: $uri=~s/\.(\w+)$/\.$version\.$1/;
10970: }
10971: }
10972: untie %bighash;
1.413 www 10973: }
1.599 albertel 10974: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10975: }
10976:
10977: sub deversion {
10978: my $url=shift;
10979: $url=~s/\.\d+\.(\w+)$/\.$1/;
10980: return $url;
1.210 www 10981: }
10982:
1.31 www 10983: # ------------------------------------------------------ Return symb list entry
10984:
10985: sub symbread {
1.249 www 10986: my ($thisfn,$donotrecurse)=@_;
1.1172.2.54 raeburn 10987: my $cache_str='request.symbread.cached.'.$thisfn;
10988: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 10989: # no filename provided? try from environment
1.1172.2.54 raeburn 10990: unless ($thisfn) {
1.620 albertel 10991: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10992: return $env{$cache_str}=&symbclean($env{'request.symb'});
10993: }
10994: $thisfn=$env{'request.filename'};
1.44 www 10995: }
1.569 albertel 10996: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10997: # is that filename actually a symb? Verify, clean, and return
10998: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10999: if (&symbverify($thisfn,$1)) {
1.620 albertel 11000: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11001: }
1.242 www 11002: }
1.44 www 11003: $thisfn=declutter($thisfn);
1.31 www 11004: my %hash;
1.37 www 11005: my %bighash;
11006: my $syval='';
1.620 albertel 11007: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11008: my $targetfn = $thisfn;
1.609 banghart 11009: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11010: $targetfn = 'adm/wrapper/'.$thisfn;
11011: }
1.687 albertel 11012: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11013: $targetfn=$1;
11014: }
1.620 albertel 11015: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11016: &GDBM_READER(),0640)) {
1.481 raeburn 11017: $syval=$hash{$targetfn};
1.37 www 11018: untie(%hash);
11019: }
11020: # ---------------------------------------------------------- There was an entry
11021: if ($syval) {
1.601 albertel 11022: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11023: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11024: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11025: #return $env{$cache_str}='';
1.601 albertel 11026: #}
11027: #$syval.=$1;
11028: #}
1.37 www 11029: } else {
11030: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11031: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11032: &GDBM_READER(),0640)) {
1.37 www 11033: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11034: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11035: unless ($ids) {
11036: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11037: }
11038: unless ($ids) {
11039: # alias?
11040: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11041: }
1.37 www 11042: if ($ids) {
11043: # ------------------------------------------------------------------- Has ID(s)
11044: my @possibilities=split(/\,/,$ids);
1.39 www 11045: if ($#possibilities==0) {
11046: # ----------------------------------------------- There is only one possibility
1.37 www 11047: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11048: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11049: $resid,$thisfn);
1.249 www 11050: } elsif (!$donotrecurse) {
1.39 www 11051: # ------------------------------------------ There is more than one possibility
11052: my $realpossible=0;
1.800 albertel 11053: foreach my $id (@possibilities) {
11054: my $file=$bighash{'src_'.$id};
1.39 www 11055: if (&allowed('bre',$file)) {
1.800 albertel 11056: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11057: if ($bighash{'map_type_'.$mapid} ne 'page') {
11058: $realpossible++;
1.626 albertel 11059: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11060: $resid,$thisfn);
1.39 www 11061: }
11062: }
1.191 harris41 11063: }
1.39 www 11064: if ($realpossible!=1) { $syval=''; }
1.249 www 11065: } else {
11066: $syval='';
1.37 www 11067: }
11068: }
11069: untie(%bighash)
1.481 raeburn 11070: }
1.31 www 11071: }
1.62 www 11072: if ($syval) {
1.620 albertel 11073: return $env{$cache_str}=$syval;
1.62 www 11074: }
1.31 www 11075: }
1.949 raeburn 11076: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11077: return $env{$cache_str}='';
1.31 www 11078: }
11079:
11080: # ---------------------------------------------------------- Return random seed
11081:
1.32 www 11082: sub numval {
11083: my $txt=shift;
11084: $txt=~tr/A-J/0-9/;
11085: $txt=~tr/a-j/0-9/;
11086: $txt=~tr/K-T/0-9/;
11087: $txt=~tr/k-t/0-9/;
11088: $txt=~tr/U-Z/0-5/;
11089: $txt=~tr/u-z/0-5/;
11090: $txt=~s/\D//g;
1.564 albertel 11091: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11092: return int($txt);
1.368 albertel 11093: }
11094:
1.484 albertel 11095: sub numval2 {
11096: my $txt=shift;
11097: $txt=~tr/A-J/0-9/;
11098: $txt=~tr/a-j/0-9/;
11099: $txt=~tr/K-T/0-9/;
11100: $txt=~tr/k-t/0-9/;
11101: $txt=~tr/U-Z/0-5/;
11102: $txt=~tr/u-z/0-5/;
11103: $txt=~s/\D//g;
11104: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11105: my $total;
11106: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11107: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11108: return int($total);
11109: }
11110:
1.575 albertel 11111: sub numval3 {
11112: use integer;
11113: my $txt=shift;
11114: $txt=~tr/A-J/0-9/;
11115: $txt=~tr/a-j/0-9/;
11116: $txt=~tr/K-T/0-9/;
11117: $txt=~tr/k-t/0-9/;
11118: $txt=~tr/U-Z/0-5/;
11119: $txt=~tr/u-z/0-5/;
11120: $txt=~s/\D//g;
11121: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11122: my $total;
11123: foreach my $val (@txts) { $total+=$val; }
11124: if ($_64bit) { $total=(($total<<32)>>32); }
11125: return $total;
11126: }
11127:
1.675 albertel 11128: sub digest {
11129: my ($data)=@_;
11130: my $digest=&Digest::MD5::md5($data);
11131: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11132: my ($e,$f);
11133: {
11134: use integer;
11135: $e=($a+$b);
11136: $f=($c+$d);
11137: if ($_64bit) {
11138: $e=(($e<<32)>>32);
11139: $f=(($f<<32)>>32);
11140: }
11141: }
11142: if (wantarray) {
11143: return ($e,$f);
11144: } else {
11145: my $g;
11146: {
11147: use integer;
11148: $g=($e+$f);
11149: if ($_64bit) {
11150: $g=(($g<<32)>>32);
11151: }
11152: }
11153: return $g;
11154: }
11155: }
11156:
1.368 albertel 11157: sub latest_rnd_algorithm_id {
1.675 albertel 11158: return '64bit5';
1.366 albertel 11159: }
1.32 www 11160:
1.503 albertel 11161: sub get_rand_alg {
11162: my ($courseid)=@_;
1.790 albertel 11163: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11164: if ($courseid) {
1.620 albertel 11165: return $env{"course.$courseid.rndseed"};
1.503 albertel 11166: }
11167: return &latest_rnd_algorithm_id();
11168: }
11169:
1.562 albertel 11170: sub validCODE {
11171: my ($CODE)=@_;
11172: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11173: return 0;
11174: }
11175:
1.491 albertel 11176: sub getCODE {
1.620 albertel 11177: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11178: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11179: defined($Apache::lonhomework::parsing_a_task) ) &&
11180: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11181: return $Apache::lonhomework::history{'resource.CODE'};
11182: }
11183: return undef;
11184: }
1.1133 foxr 11185: #
11186: # Determines the random seed for a specific context:
11187: #
11188: # parameters:
11189: # symb - in course context the symb for the seed.
11190: # course_id - The course id of the form domain_coursenum.
11191: # domain - Domain for the user.
11192: # course - Course for the user.
11193: # cenv - environment of the course.
11194: #
11195: # NOTE:
11196: # All parameters are picked out of the environment if missing
11197: # or not defined.
11198: # If a symb cannot be determined the current time is used instead.
11199: #
11200: # For a given well defined symb, courside, domain, username,
11201: # and course environment, the seed is reproducible.
11202: #
1.31 www 11203: sub rndseed {
1.1133 foxr 11204: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11205: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11206: if (!defined($symb)) {
1.366 albertel 11207: unless ($symb=$wsymb) { return time; }
11208: }
1.1146 foxr 11209: if (!defined $courseid) {
11210: $courseid=$wcourseid;
11211: }
11212: if (!defined $domain) { $domain=$wdomain; }
11213: if (!defined $username) { $username=$wusername }
1.1133 foxr 11214:
11215: my $which;
11216: if (defined($cenv->{'rndseed'})) {
11217: $which = $cenv->{'rndseed'};
11218: } else {
11219: $which =&get_rand_alg($courseid);
11220: }
1.491 albertel 11221: if (defined(&getCODE())) {
1.675 albertel 11222: if ($which eq '64bit5') {
11223: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11224: } elsif ($which eq '64bit4') {
1.575 albertel 11225: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11226: } else {
11227: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11228: }
1.675 albertel 11229: } elsif ($which eq '64bit5') {
11230: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11231: } elsif ($which eq '64bit4') {
11232: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11233: } elsif ($which eq '64bit3') {
11234: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11235: } elsif ($which eq '64bit2') {
11236: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11237: } elsif ($which eq '64bit') {
11238: return &rndseed_64bit($symb,$courseid,$domain,$username);
11239: }
11240: return &rndseed_32bit($symb,$courseid,$domain,$username);
11241: }
11242:
11243: sub rndseed_32bit {
11244: my ($symb,$courseid,$domain,$username)=@_;
11245: {
11246: use integer;
11247: my $symbchck=unpack("%32C*",$symb) << 27;
11248: my $symbseed=numval($symb) << 22;
11249: my $namechck=unpack("%32C*",$username) << 17;
11250: my $nameseed=numval($username) << 12;
11251: my $domainseed=unpack("%32C*",$domain) << 7;
11252: my $courseseed=unpack("%32C*",$courseid);
11253: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11254: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11255: #&logthis("rndseed :$num:$symb");
1.564 albertel 11256: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11257: return $num;
11258: }
11259: }
11260:
11261: sub rndseed_64bit {
11262: my ($symb,$courseid,$domain,$username)=@_;
11263: {
11264: use integer;
11265: my $symbchck=unpack("%32S*",$symb) << 21;
11266: my $symbseed=numval($symb) << 10;
11267: my $namechck=unpack("%32S*",$username);
11268:
11269: my $nameseed=numval($username) << 21;
11270: my $domainseed=unpack("%32S*",$domain) << 10;
11271: my $courseseed=unpack("%32S*",$courseid);
11272:
11273: my $num1=$symbchck+$symbseed+$namechck;
11274: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11275: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11276: #&logthis("rndseed :$num:$symb");
1.564 albertel 11277: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11278: return "$num1,$num2";
1.155 albertel 11279: }
1.366 albertel 11280: }
11281:
1.443 albertel 11282: sub rndseed_64bit2 {
11283: my ($symb,$courseid,$domain,$username)=@_;
11284: {
11285: use integer;
11286: # strings need to be an even # of cahracters long, it it is odd the
11287: # last characters gets thrown away
11288: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11289: my $symbseed=numval($symb) << 10;
11290: my $namechck=unpack("%32S*",$username.' ');
11291:
11292: my $nameseed=numval($username) << 21;
1.501 albertel 11293: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11294: my $courseseed=unpack("%32S*",$courseid.' ');
11295:
11296: my $num1=$symbchck+$symbseed+$namechck;
11297: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11298: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11299: #&logthis("rndseed :$num:$symb");
1.803 albertel 11300: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11301: return "$num1,$num2";
11302: }
11303: }
11304:
11305: sub rndseed_64bit3 {
11306: my ($symb,$courseid,$domain,$username)=@_;
11307: {
11308: use integer;
11309: # strings need to be an even # of cahracters long, it it is odd the
11310: # last characters gets thrown away
11311: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11312: my $symbseed=numval2($symb) << 10;
11313: my $namechck=unpack("%32S*",$username.' ');
11314:
11315: my $nameseed=numval2($username) << 21;
1.443 albertel 11316: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11317: my $courseseed=unpack("%32S*",$courseid.' ');
11318:
11319: my $num1=$symbchck+$symbseed+$namechck;
11320: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11321: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11322: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11323: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11324:
1.503 albertel 11325: return "$num1:$num2";
1.443 albertel 11326: }
11327: }
11328:
1.575 albertel 11329: sub rndseed_64bit4 {
11330: my ($symb,$courseid,$domain,$username)=@_;
11331: {
11332: use integer;
11333: # strings need to be an even # of cahracters long, it it is odd the
11334: # last characters gets thrown away
11335: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11336: my $symbseed=numval3($symb) << 10;
11337: my $namechck=unpack("%32S*",$username.' ');
11338:
11339: my $nameseed=numval3($username) << 21;
11340: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11341: my $courseseed=unpack("%32S*",$courseid.' ');
11342:
11343: my $num1=$symbchck+$symbseed+$namechck;
11344: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11345: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11346: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11347: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11348:
1.575 albertel 11349: return "$num1:$num2";
11350: }
11351: }
11352:
1.675 albertel 11353: sub rndseed_64bit5 {
11354: my ($symb,$courseid,$domain,$username)=@_;
11355: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11356: return "$num1:$num2";
11357: }
11358:
1.366 albertel 11359: sub rndseed_CODE_64bit {
11360: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11361: {
1.366 albertel 11362: use integer;
1.443 albertel 11363: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11364: my $symbseed=numval2($symb);
1.491 albertel 11365: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11366: my $CODEseed=numval(&getCODE());
1.443 albertel 11367: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11368: my $num1=$symbseed+$CODEchck;
11369: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11370: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11371: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11372: if ($_64bit) { $num1=(($num1<<32)>>32); }
11373: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11374: return "$num1:$num2";
1.366 albertel 11375: }
11376: }
11377:
1.575 albertel 11378: sub rndseed_CODE_64bit4 {
11379: my ($symb,$courseid,$domain,$username)=@_;
11380: {
11381: use integer;
11382: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11383: my $symbseed=numval3($symb);
11384: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11385: my $CODEseed=numval3(&getCODE());
11386: my $courseseed=unpack("%32S*",$courseid.' ');
11387: my $num1=$symbseed+$CODEchck;
11388: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11389: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11390: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11391: if ($_64bit) { $num1=(($num1<<32)>>32); }
11392: if ($_64bit) { $num2=(($num2<<32)>>32); }
11393: return "$num1:$num2";
11394: }
11395: }
11396:
1.675 albertel 11397: sub rndseed_CODE_64bit5 {
11398: my ($symb,$courseid,$domain,$username)=@_;
11399: my $code = &getCODE();
11400: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11401: return "$num1:$num2";
11402: }
11403:
1.366 albertel 11404: sub setup_random_from_rndseed {
11405: my ($rndseed)=@_;
1.503 albertel 11406: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11407: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11408: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11409: &Math::Random::random_set_seed_from_phrase($rndseed);
11410: } else {
11411: &Math::Random::random_set_seed($num1,$num2);
11412: }
1.366 albertel 11413: } else {
11414: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11415: }
1.36 albertel 11416: }
11417:
1.474 albertel 11418: sub latest_receipt_algorithm_id {
1.835 albertel 11419: return 'receipt3';
1.474 albertel 11420: }
11421:
1.480 www 11422: sub recunique {
11423: my $fucourseid=shift;
11424: my $unique;
1.835 albertel 11425: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11426: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11427: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11428: } else {
11429: $unique=$perlvar{'lonReceipt'};
11430: }
11431: return unpack("%32C*",$unique);
11432: }
11433:
11434: sub recprefix {
11435: my $fucourseid=shift;
11436: my $prefix;
1.835 albertel 11437: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11438: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11439: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11440: } else {
11441: $prefix=$perlvar{'lonHostID'};
11442: }
11443: return unpack("%32C*",$prefix);
11444: }
11445:
1.76 www 11446: sub ireceipt {
1.474 albertel 11447: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11448:
11449: my $return =&recprefix($fucourseid).'-';
11450:
11451: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11452: $env{'request.state'} eq 'construct') {
11453: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11454: return $return;
11455: }
11456:
1.76 www 11457: my $cuname=unpack("%32C*",$funame);
11458: my $cudom=unpack("%32C*",$fudom);
11459: my $cucourseid=unpack("%32C*",$fucourseid);
11460: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11461: my $cunique=&recunique($fucourseid);
1.474 albertel 11462: my $cpart=unpack("%32S*",$part);
1.835 albertel 11463: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11464:
1.790 albertel 11465: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11466:
11467: $return.= ($cunique%$cuname+
11468: $cunique%$cudom+
11469: $cusymb%$cuname+
11470: $cusymb%$cudom+
11471: $cucourseid%$cuname+
11472: $cucourseid%$cudom+
11473: $cpart%$cuname+
11474: $cpart%$cudom);
11475: } else {
11476: $return.= ($cunique%$cuname+
11477: $cunique%$cudom+
11478: $cusymb%$cuname+
11479: $cusymb%$cudom+
11480: $cucourseid%$cuname+
11481: $cucourseid%$cudom);
11482: }
11483: return $return;
1.76 www 11484: }
11485:
11486: sub receipt {
1.474 albertel 11487: my ($part)=@_;
1.790 albertel 11488: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11489: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11490: }
1.260 ng 11491:
1.790 albertel 11492: sub whichuser {
11493: my ($passedsymb)=@_;
11494: my ($symb,$courseid,$domain,$name,$publicuser);
11495: if (defined($env{'form.grade_symb'})) {
11496: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11497: my $allowed=&allowed('vgr',$tmp_courseid);
11498: if (!$allowed &&
11499: exists($env{'request.course.sec'}) &&
11500: $env{'request.course.sec'} !~ /^\s*$/) {
11501: $allowed=&allowed('vgr',$tmp_courseid.
11502: '/'.$env{'request.course.sec'});
11503: }
11504: if ($allowed) {
11505: ($symb)=&get_env_multiple('form.grade_symb');
11506: $courseid=$tmp_courseid;
11507: ($domain)=&get_env_multiple('form.grade_domain');
11508: ($name)=&get_env_multiple('form.grade_username');
11509: return ($symb,$courseid,$domain,$name,$publicuser);
11510: }
11511: }
11512: if (!$passedsymb) {
11513: $symb=&symbread();
11514: } else {
11515: $symb=$passedsymb;
11516: }
11517: $courseid=$env{'request.course.id'};
11518: $domain=$env{'user.domain'};
11519: $name=$env{'user.name'};
11520: if ($name eq 'public' && $domain eq 'public') {
11521: if (!defined($env{'form.username'})) {
11522: $env{'form.username'}.=time.rand(10000000);
11523: }
11524: $name.=$env{'form.username'};
11525: }
11526: return ($symb,$courseid,$domain,$name,$publicuser);
11527:
11528: }
11529:
1.36 albertel 11530: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11531: # returns either the contents of the file or
11532: # -1 if the file doesn't exist
1.481 raeburn 11533: #
11534: # if the target is a file that was uploaded via DOCS,
11535: # a check will be made to see if a current copy exists on the local server,
11536: # if it does this will be served, otherwise a copy will be retrieved from
11537: # the home server for the course and stored in /home/httpd/html/userfiles on
11538: # the local server.
1.472 albertel 11539:
1.36 albertel 11540: sub getfile {
1.538 albertel 11541: my ($file) = @_;
1.609 banghart 11542: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11543: &repcopy($file);
11544: return &readfile($file);
11545: }
11546:
11547: sub repcopy_userfile {
11548: my ($file)=@_;
1.1142 raeburn 11549: my $londocroot = $perlvar{'lonDocRoot'};
11550: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11551: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11552: my ($cdom,$cnum,$filename) =
1.811 albertel 11553: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11554: my $uri="/uploaded/$cdom/$cnum/$filename";
11555: if (-e "$file") {
1.828 www 11556: # we already have a local copy, check it out
1.538 albertel 11557: my @fileinfo = stat($file);
1.828 www 11558: my $rtncode;
11559: my $info;
1.538 albertel 11560: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11561: if ($lwpresp ne 'ok') {
1.828 www 11562: # there is no such file anymore, even though we had a local copy
1.482 albertel 11563: if ($rtncode eq '404') {
1.538 albertel 11564: unlink($file);
1.482 albertel 11565: }
11566: return -1;
11567: }
11568: if ($info < $fileinfo[9]) {
1.828 www 11569: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11570: return 'ok';
1.828 www 11571: } else {
11572: # the file is outdated, get rid of it
11573: unlink($file);
1.482 albertel 11574: }
1.828 www 11575: }
11576: # one way or the other, at this point, we don't have the file
11577: # construct the correct path for the file
11578: my @parts = ($cdom,$cnum);
11579: if ($filename =~ m|^(.+)/[^/]+$|) {
11580: push @parts, split(/\//,$1);
11581: }
11582: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11583: foreach my $part (@parts) {
11584: $path .= '/'.$part;
11585: if (!-e $path) {
11586: mkdir($path,0770);
1.482 albertel 11587: }
11588: }
1.828 www 11589: # now the path exists for sure
11590: # get a user agent
11591: my $ua=new LWP::UserAgent;
11592: my $transferfile=$file.'.in.transfer';
11593: # FIXME: this should flock
11594: if (-e $transferfile) { return 'ok'; }
11595: my $request;
11596: $uri=~s/^\///;
1.980 raeburn 11597: my $homeserver = &homeserver($cnum,$cdom);
11598: my $protocol = $protocol{$homeserver};
11599: $protocol = 'http' if ($protocol ne 'https');
11600: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11601: my $response=$ua->request($request,$transferfile);
11602: # did it work?
11603: if ($response->is_error()) {
11604: unlink($transferfile);
11605: &logthis("Userfile repcopy failed for $uri");
11606: return -1;
11607: }
11608: # worked, rename the transfer file
11609: rename($transferfile,$file);
1.607 raeburn 11610: return 'ok';
1.481 raeburn 11611: }
11612:
1.517 albertel 11613: sub tokenwrapper {
11614: my $uri=shift;
1.980 raeburn 11615: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11616: $uri=~s|^/||;
1.620 albertel 11617: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11618: my $token=$1;
1.552 albertel 11619: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11620: if ($udom && $uname && $file) {
11621: $file=~s|(\?\.*)*$||;
1.949 raeburn 11622: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11623: my $homeserver = &homeserver($uname,$udom);
11624: my $protocol = $protocol{$homeserver};
11625: $protocol = 'http' if ($protocol ne 'https');
11626: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11627: (($uri=~/\?/)?'&':'?').'token='.$token.
11628: '&tokenissued='.$perlvar{'lonHostID'};
11629: } else {
11630: return '/adm/notfound.html';
11631: }
11632: }
11633:
1.828 www 11634: # call with reqtype HEAD: get last modification time
11635: # call with reqtype GET: get the file contents
11636: # Do not call this with reqtype GET for large files! It loads everything into memory
11637: #
1.481 raeburn 11638: sub getuploaded {
11639: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11640: $uri=~s/^\///;
1.980 raeburn 11641: my $homeserver = &homeserver($cnum,$cdom);
11642: my $protocol = $protocol{$homeserver};
11643: $protocol = 'http' if ($protocol ne 'https');
11644: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11645: my $ua=new LWP::UserAgent;
11646: my $request=new HTTP::Request($reqtype,$uri);
11647: my $response=$ua->request($request);
11648: $$rtncode = $response->code;
1.482 albertel 11649: if (! $response->is_success()) {
11650: return 'failed';
11651: }
11652: if ($reqtype eq 'HEAD') {
1.486 www 11653: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11654: } elsif ($reqtype eq 'GET') {
11655: $$info = $response->content;
1.472 albertel 11656: }
1.482 albertel 11657: return 'ok';
1.36 albertel 11658: }
11659:
1.481 raeburn 11660: sub readfile {
11661: my $file = shift;
11662: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11663: my $fh;
11664: open($fh,"<$file");
11665: my $a='';
1.800 albertel 11666: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11667: return $a;
11668: }
11669:
1.36 albertel 11670: sub filelocation {
1.590 banghart 11671: my ($dir,$file) = @_;
11672: my $location;
11673: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11674:
11675: if ($file =~ m-^/adm/-) {
11676: $file=~s-^/adm/wrapper/-/-;
11677: $file=~s-^/adm/coursedocs/showdoc/-/-;
11678: }
1.882 albertel 11679:
1.1139 www 11680: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11681: $location = $file;
1.609 banghart 11682: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11683: my ($udom,$uname,$filename)=
1.811 albertel 11684: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11685: my $home=&homeserver($uname,$udom);
11686: my $is_me=0;
11687: my @ids=¤t_machine_ids();
11688: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11689: if ($is_me) {
1.1117 foxr 11690: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11691: } else {
11692: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11693: $udom.'/'.$uname.'/'.$filename;
11694: }
1.882 albertel 11695: } elsif ($file =~ m-^/adm/-) {
11696: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11697: } else {
11698: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11699: $file=~s:^/(res|priv)/:/:;
11700: my $space=$1;
1.590 banghart 11701: if ( !( $file =~ m:^/:) ) {
11702: $location = $dir. '/'.$file;
11703: } else {
1.1142 raeburn 11704: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11705: }
1.59 albertel 11706: }
1.590 banghart 11707: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11708: while ($location=~m{/\.\./}) {
11709: if ($location =~ m{/[^/]+/\.\./}) {
11710: $location=~ s{/[^/]+/\.\./}{/}g;
11711: } else {
11712: $location=~ s{/\.\./}{/}g;
11713: }
11714: } #remove dir/..
1.590 banghart 11715: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11716: return $location;
1.46 www 11717: }
1.36 albertel 11718:
1.46 www 11719: sub hreflocation {
11720: my ($dir,$file)=@_;
1.980 raeburn 11721: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11722: $file=filelocation($dir,$file);
1.700 albertel 11723: } elsif ($file=~m-^/adm/-) {
11724: $file=~s-^/adm/wrapper/-/-;
11725: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11726: }
11727: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11728: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11729: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11730: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11731: {/uploaded/$1/$2/}x;
1.46 www 11732: }
1.913 albertel 11733: if ($file=~ m{^/userfiles/}) {
11734: $file =~ s{^/userfiles/}{/uploaded/};
11735: }
1.462 albertel 11736: return $file;
1.465 albertel 11737: }
11738:
1.1139 www 11739:
11740:
11741:
11742:
1.465 albertel 11743: sub current_machine_domains {
1.853 albertel 11744: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11745: }
11746:
11747: sub machine_domains {
11748: my ($hostname) = @_;
1.465 albertel 11749: my @domains;
1.838 albertel 11750: my %hostname = &all_hostnames();
1.465 albertel 11751: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11752: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11753: if ($hostname eq $name) {
1.844 albertel 11754: push(@domains,&host_domain($id));
1.465 albertel 11755: }
11756: }
11757: return @domains;
11758: }
11759:
11760: sub current_machine_ids {
1.853 albertel 11761: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11762: }
11763:
11764: sub machine_ids {
11765: my ($hostname) = @_;
11766: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11767: my @ids;
1.888 albertel 11768: my %name_to_host = &all_names();
1.889 albertel 11769: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11770: return @{ $name_to_host{$hostname} };
11771: }
11772: return;
1.31 www 11773: }
11774:
1.824 raeburn 11775: sub additional_machine_domains {
11776: my @domains;
11777: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11778: while( my $line = <$fh>) {
11779: $line =~ s/\s//g;
11780: push(@domains,$line);
11781: }
11782: return @domains;
11783: }
11784:
11785: sub default_login_domain {
11786: my $domain = $perlvar{'lonDefDomain'};
11787: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11788: foreach my $posdom (¤t_machine_domains(),
11789: &additional_machine_domains()) {
11790: if (lc($posdom) eq lc($testdomain)) {
11791: $domain=$posdom;
11792: last;
11793: }
11794: }
11795: return $domain;
11796: }
11797:
1.31 www 11798: # ------------------------------------------------------------- Declutters URLs
11799:
11800: sub declutter {
11801: my $thisfn=shift;
1.569 albertel 11802: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 11803: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11804: $thisfn=~s{^/home/httpd/html}{};
11805: }
1.31 www 11806: $thisfn=~s/^\///;
1.697 albertel 11807: $thisfn=~s|^adm/wrapper/||;
11808: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11809: $thisfn=~s/^res\///;
1.1172 bisitz 11810: $thisfn=~s/^priv\///;
1.1032 raeburn 11811: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11812: $thisfn=~s/\?.+$//;
11813: }
1.268 www 11814: return $thisfn;
11815: }
11816:
11817: # ------------------------------------------------------------- Clutter up URLs
11818:
11819: sub clutter {
11820: my $thisfn='/'.&declutter(shift);
1.887 albertel 11821: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11822: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11823: $thisfn='/res'.$thisfn;
11824: }
1.1031 raeburn 11825: if ($thisfn !~m|^/adm|) {
11826: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11827: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11828: } else {
11829: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11830: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11831: if ($embstyle eq 'ssi'
11832: || ($embstyle eq 'hdn')
11833: || ($embstyle eq 'rat')
11834: || ($embstyle eq 'prv')
11835: || ($embstyle eq 'ign')) {
11836: #do nothing with these
11837: } elsif (($embstyle eq 'img')
1.695 albertel 11838: || ($embstyle eq 'emb')
11839: || ($embstyle eq 'wrp')) {
11840: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11841: } elsif ($embstyle eq 'unk'
11842: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11843: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11844: } else {
1.718 www 11845: # &logthis("Got a blank emb style");
1.695 albertel 11846: }
1.694 albertel 11847: }
11848: }
1.31 www 11849: return $thisfn;
1.12 www 11850: }
11851:
1.787 albertel 11852: sub clutter_with_no_wrapper {
11853: my $uri = &clutter(shift);
11854: if ($uri =~ m-^/adm/-) {
11855: $uri =~ s-^/adm/wrapper/-/-;
11856: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11857: }
11858: return $uri;
11859: }
11860:
1.557 albertel 11861: sub freeze_escape {
11862: my ($value)=@_;
11863: if (ref($value)) {
11864: $value=&nfreeze($value);
11865: return '__FROZEN__'.&escape($value);
11866: }
11867: return &escape($value);
11868: }
11869:
1.11 www 11870:
1.557 albertel 11871: sub thaw_unescape {
11872: my ($value)=@_;
11873: if ($value =~ /^__FROZEN__/) {
11874: substr($value,0,10,undef);
11875: $value=&unescape($value);
11876: return &thaw($value);
11877: }
11878: return &unescape($value);
11879: }
11880:
1.436 albertel 11881: sub correct_line_ends {
11882: my ($result)=@_;
11883: $$result =~s/\r\n/\n/mg;
11884: $$result =~s/\r/\n/mg;
1.415 albertel 11885: }
1.1 albertel 11886: # ================================================================ Main Program
11887:
1.184 www 11888: sub goodbye {
1.204 albertel 11889: &logthis("Starting Shut down");
1.443 albertel 11890: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11891: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11892: #converted
1.599 albertel 11893: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11894: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11895: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11896: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11897: #1.1 only
1.870 albertel 11898: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11899: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11900: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11901: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11902: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11903: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11904: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11905: &flushcourselogs();
11906: &logthis("Shutting down");
11907: }
11908:
1.852 albertel 11909: sub get_dns {
1.1172.2.17 raeburn 11910: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11911: if (!$ignore_cache) {
11912: my ($content,$cached)=
11913: &Apache::lonnet::is_cached_new('dns',$url);
11914: if ($cached) {
1.1172.2.17 raeburn 11915: &$func($content,$hashref);
1.869 albertel 11916: return;
11917: }
11918: }
11919:
11920: my %alldns;
1.852 albertel 11921: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11922: foreach my $dns (<$config>) {
11923: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11924: my $line = $1;
11925: my ($host,$protocol) = split(/:/,$line);
11926: if ($protocol ne 'https') {
11927: $protocol = 'http';
11928: }
11929: $alldns{$host} = $protocol;
1.869 albertel 11930: }
11931: while (%alldns) {
1.1172.2.52 raeburn 11932: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 11933: my $ua=new LWP::UserAgent;
1.1134 raeburn 11934: $ua->timeout(30);
1.979 raeburn 11935: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11936: my $response=$ua->request($request);
1.979 raeburn 11937: delete($alldns{$dns});
1.852 albertel 11938: next if ($response->is_error());
11939: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11940: unless ($nocache) {
1.1172.2.23 raeburn 11941: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11942: }
11943: &$func(\@content,$hashref);
1.869 albertel 11944: return;
1.852 albertel 11945: }
11946: close($config);
1.871 albertel 11947: my $which = (split('/',$url))[3];
11948: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11949: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11950: my @content = <$config>;
1.1172.2.17 raeburn 11951: &$func(\@content,$hashref);
11952: return;
11953: }
11954:
11955: # ------------------------------------------------------Get DNS checksums file
11956: sub parse_dns_checksums_tab {
11957: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 11958: my $lonhost = $perlvar{'lonHostID'};
11959: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 11960: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 11961: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11962: my $webconfdir = '/etc/httpd/conf';
11963: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11964: $webconfdir = '/etc/apache2';
11965: } elsif ($distro =~ /^sles(\d+)$/) {
11966: if ($1 >= 10) {
11967: $webconfdir = '/etc/apache2';
11968: }
11969: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11970: if ($1 >= 10.0) {
11971: $webconfdir = '/etc/apache2';
11972: }
11973: }
1.1172.2.17 raeburn 11974: my ($release,$timestamp) = split(/\-/,$loncaparev);
11975: my (%chksum,%revnum);
11976: if (ref($lines) eq 'ARRAY') {
11977: chomp(@{$lines});
1.1172.2.34 raeburn 11978: my $version = shift(@{$lines});
11979: if ($version eq $release) {
1.1172.2.17 raeburn 11980: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11981: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 11982: if ($file =~ m{^/etc/httpd/conf}) {
11983: if ($webconfdir eq '/etc/apache2') {
11984: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11985: }
11986: }
1.1172.2.34 raeburn 11987: $chksum{$file} = $shasum;
11988: $revnum{$file} = $version;
1.1172.2.17 raeburn 11989: }
11990: if (ref($hashref) eq 'HASH') {
11991: %{$hashref} = (
11992: sums => \%chksum,
11993: versions => \%revnum,
11994: );
11995: }
11996: }
11997: }
1.869 albertel 11998: return;
1.852 albertel 11999: }
1.1172.2.17 raeburn 12000:
12001: sub fetch_dns_checksums {
12002: my %checksums;
1.1172.2.34 raeburn 12003: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12004: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12005: my ($release,$timestamp) = split(/\-/,$loncaparev);
12006: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12007: \%checksums);
12008: return \%checksums;
12009: }
12010:
1.327 albertel 12011: # ------------------------------------------------------------ Read domain file
12012: {
1.852 albertel 12013: my $loaded;
1.846 albertel 12014: my %domain;
12015:
1.852 albertel 12016: sub parse_domain_tab {
12017: my ($lines) = @_;
12018: foreach my $line (@$lines) {
12019: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12020:
1.846 albertel 12021: chomp($line);
1.852 albertel 12022: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12023: my %this_domain;
12024: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12025: 'lang_def', 'city', 'longi', 'lati',
12026: 'primary') {
12027: $this_domain{$field} = shift(@elements);
12028: }
12029: $domain{$name} = \%this_domain;
1.852 albertel 12030: }
12031: }
1.864 albertel 12032:
12033: sub reset_domain_info {
12034: undef($loaded);
12035: undef(%domain);
12036: }
12037:
1.852 albertel 12038: sub load_domain_tab {
1.869 albertel 12039: my ($ignore_cache) = @_;
12040: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12041: my $fh;
12042: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12043: my @lines = <$fh>;
12044: &parse_domain_tab(\@lines);
1.448 albertel 12045: }
1.852 albertel 12046: close($fh);
12047: $loaded = 1;
1.327 albertel 12048: }
1.846 albertel 12049:
12050: sub domain {
1.852 albertel 12051: &load_domain_tab() if (!$loaded);
12052:
1.846 albertel 12053: my ($name,$what) = @_;
12054: return if ( !exists($domain{$name}) );
12055:
12056: if (!$what) {
12057: return $domain{$name}{'description'};
12058: }
12059: return $domain{$name}{$what};
12060: }
1.974 raeburn 12061:
12062: sub domain_info {
12063: &load_domain_tab() if (!$loaded);
12064: return %domain;
12065: }
12066:
1.327 albertel 12067: }
12068:
12069:
1.1 albertel 12070: # ------------------------------------------------------------- Read hosts file
12071: {
1.838 albertel 12072: my %hostname;
1.844 albertel 12073: my %hostdom;
1.845 albertel 12074: my %libserv;
1.852 albertel 12075: my $loaded;
1.888 albertel 12076: my %name_to_host;
1.1074 raeburn 12077: my %internetdom;
1.1107 raeburn 12078: my %LC_dns_serv;
1.852 albertel 12079:
12080: sub parse_hosts_tab {
12081: my ($file) = @_;
12082: foreach my $configline (@$file) {
12083: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12084: chomp($configline);
12085: if ($configline =~ /^\^/) {
12086: if ($configline =~ /^\^([\w.\-]+)/) {
12087: $LC_dns_serv{$1} = 1;
12088: }
12089: next;
12090: }
1.1074 raeburn 12091: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12092: $name=~s/\s//g;
12093: if ($id && $domain && $role && $name) {
12094: $hostname{$id}=$name;
1.888 albertel 12095: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12096: $hostdom{$id}=$domain;
12097: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12098: if (defined($protocol)) {
12099: if ($protocol eq 'https') {
12100: $protocol{$id} = $protocol;
12101: } else {
12102: $protocol{$id} = 'http';
12103: }
1.968 raeburn 12104: } else {
1.969 raeburn 12105: $protocol{$id} = 'http';
1.968 raeburn 12106: }
1.1074 raeburn 12107: if (defined($intdom)) {
12108: $internetdom{$id} = $intdom;
12109: }
1.852 albertel 12110: }
12111: }
12112: }
1.864 albertel 12113:
12114: sub reset_hosts_info {
1.897 albertel 12115: &purge_remembered();
1.864 albertel 12116: &reset_domain_info();
12117: &reset_hosts_ip_info();
1.892 albertel 12118: undef(%name_to_host);
1.864 albertel 12119: undef(%hostname);
12120: undef(%hostdom);
12121: undef(%libserv);
12122: undef($loaded);
12123: }
1.1 albertel 12124:
1.852 albertel 12125: sub load_hosts_tab {
1.869 albertel 12126: my ($ignore_cache) = @_;
12127: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12128: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12129: my @config = <$config>;
12130: &parse_hosts_tab(\@config);
12131: close($config);
12132: $loaded=1;
1.1 albertel 12133: }
1.852 albertel 12134:
1.838 albertel 12135: sub hostname {
1.852 albertel 12136: &load_hosts_tab() if (!$loaded);
12137:
1.838 albertel 12138: my ($lonid) = @_;
12139: return $hostname{$lonid};
12140: }
1.845 albertel 12141:
1.838 albertel 12142: sub all_hostnames {
1.852 albertel 12143: &load_hosts_tab() if (!$loaded);
12144:
1.838 albertel 12145: return %hostname;
12146: }
1.845 albertel 12147:
1.888 albertel 12148: sub all_names {
12149: &load_hosts_tab() if (!$loaded);
12150:
12151: return %name_to_host;
12152: }
12153:
1.974 raeburn 12154: sub all_host_domain {
12155: &load_hosts_tab() if (!$loaded);
12156: return %hostdom;
12157: }
12158:
1.845 albertel 12159: sub is_library {
1.852 albertel 12160: &load_hosts_tab() if (!$loaded);
12161:
1.845 albertel 12162: return exists($libserv{$_[0]});
12163: }
12164:
12165: sub all_library {
1.852 albertel 12166: &load_hosts_tab() if (!$loaded);
12167:
1.845 albertel 12168: return %libserv;
12169: }
12170:
1.1062 droeschl 12171: sub unique_library {
12172: #2x reverse removes all hostnames that appear more than once
12173: my %unique = reverse &all_library();
12174: return reverse %unique;
12175: }
12176:
1.841 albertel 12177: sub get_servers {
1.852 albertel 12178: &load_hosts_tab() if (!$loaded);
12179:
1.841 albertel 12180: my ($domain,$type) = @_;
12181: my %possible_hosts = ($type eq 'library') ? %libserv
12182: : %hostname;
12183: my %result;
1.842 albertel 12184: if (ref($domain) eq 'ARRAY') {
12185: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12186: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12187: $result{$host} = $hostname;
12188: }
12189: }
12190: } else {
12191: while ( my ($host,$hostname) = each(%possible_hosts)) {
12192: if ($hostdom{$host} eq $domain) {
12193: $result{$host} = $hostname;
12194: }
1.841 albertel 12195: }
12196: }
12197: return %result;
12198: }
1.845 albertel 12199:
1.1062 droeschl 12200: sub get_unique_servers {
12201: my %unique = reverse &get_servers(@_);
12202: return reverse %unique;
12203: }
12204:
1.844 albertel 12205: sub host_domain {
1.852 albertel 12206: &load_hosts_tab() if (!$loaded);
12207:
1.844 albertel 12208: my ($lonid) = @_;
12209: return $hostdom{$lonid};
12210: }
12211:
1.841 albertel 12212: sub all_domains {
1.852 albertel 12213: &load_hosts_tab() if (!$loaded);
12214:
1.841 albertel 12215: my %seen;
12216: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12217: return @uniq;
12218: }
1.1074 raeburn 12219:
12220: sub internet_dom {
12221: &load_hosts_tab() if (!$loaded);
12222:
12223: my ($lonid) = @_;
12224: return $internetdom{$lonid};
12225: }
1.1107 raeburn 12226:
12227: sub is_LC_dns {
12228: &load_hosts_tab() if (!$loaded);
12229:
12230: my ($hostname) = @_;
12231: return exists($LC_dns_serv{$hostname});
12232: }
12233:
1.1 albertel 12234: }
12235:
1.847 albertel 12236: {
12237: my %iphost;
1.856 albertel 12238: my %name_to_ip;
12239: my %lonid_to_ip;
1.869 albertel 12240:
1.847 albertel 12241: sub get_hosts_from_ip {
12242: my ($ip) = @_;
12243: my %iphosts = &get_iphost();
12244: if (ref($iphosts{$ip})) {
12245: return @{$iphosts{$ip}};
12246: }
12247: return;
1.839 albertel 12248: }
1.864 albertel 12249:
12250: sub reset_hosts_ip_info {
12251: undef(%iphost);
12252: undef(%name_to_ip);
12253: undef(%lonid_to_ip);
12254: }
1.856 albertel 12255:
12256: sub get_host_ip {
12257: my ($lonid) = @_;
12258: if (exists($lonid_to_ip{$lonid})) {
12259: return $lonid_to_ip{$lonid};
12260: }
12261: my $name=&hostname($lonid);
12262: my $ip = gethostbyname($name);
12263: return if (!$ip || length($ip) ne 4);
12264: $ip=inet_ntoa($ip);
12265: $name_to_ip{$name} = $ip;
12266: $lonid_to_ip{$lonid} = $ip;
12267: return $ip;
12268: }
1.847 albertel 12269:
12270: sub get_iphost {
1.869 albertel 12271: my ($ignore_cache) = @_;
1.894 albertel 12272:
1.869 albertel 12273: if (!$ignore_cache) {
12274: if (%iphost) {
12275: return %iphost;
12276: }
12277: my ($ip_info,$cached)=
12278: &Apache::lonnet::is_cached_new('iphost','iphost');
12279: if ($cached) {
12280: %iphost = %{$ip_info->[0]};
12281: %name_to_ip = %{$ip_info->[1]};
12282: %lonid_to_ip = %{$ip_info->[2]};
12283: return %iphost;
12284: }
12285: }
1.894 albertel 12286:
12287: # get yesterday's info for fallback
12288: my %old_name_to_ip;
12289: my ($ip_info,$cached)=
12290: &Apache::lonnet::is_cached_new('iphost','iphost');
12291: if ($cached) {
12292: %old_name_to_ip = %{$ip_info->[1]};
12293: }
12294:
1.888 albertel 12295: my %name_to_host = &all_names();
12296: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12297: my $ip;
12298: if (!exists($name_to_ip{$name})) {
12299: $ip = gethostbyname($name);
12300: if (!$ip || length($ip) ne 4) {
1.894 albertel 12301: if (defined($old_name_to_ip{$name})) {
12302: $ip = $old_name_to_ip{$name};
12303: &logthis("Can't find $name defaulting to old $ip");
12304: } else {
12305: &logthis("Name $name no IP found");
12306: next;
12307: }
12308: } else {
12309: $ip=inet_ntoa($ip);
1.847 albertel 12310: }
12311: $name_to_ip{$name} = $ip;
12312: } else {
12313: $ip = $name_to_ip{$name};
1.653 albertel 12314: }
1.888 albertel 12315: foreach my $id (@{ $name_to_host{$name} }) {
12316: $lonid_to_ip{$id} = $ip;
12317: }
12318: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12319: }
1.1172.2.23 raeburn 12320: &do_cache_new('iphost','iphost',
12321: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12322: 48*60*60);
1.869 albertel 12323:
1.847 albertel 12324: return %iphost;
1.598 albertel 12325: }
12326:
1.992 raeburn 12327: #
12328: # Given a DNS returns the loncapa host name for that DNS
12329: #
12330: sub host_from_dns {
12331: my ($dns) = @_;
12332: my @hosts;
12333: my $ip;
12334:
1.993 raeburn 12335: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12336: $ip = $name_to_ip{$dns};
12337: }
12338: if (!$ip) {
12339: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12340: if (length($ip) == 4) {
12341: $ip = &IO::Socket::inet_ntoa($ip);
12342: }
12343: }
12344: if ($ip) {
12345: @hosts = get_hosts_from_ip($ip);
12346: return $hosts[0];
12347: }
12348: return undef;
1.986 foxr 12349: }
1.992 raeburn 12350:
1.1074 raeburn 12351: sub get_internet_names {
12352: my ($lonid) = @_;
12353: return if ($lonid eq '');
12354: my ($idnref,$cached)=
12355: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12356: if ($cached) {
12357: return $idnref;
12358: }
12359: my $ip = &get_host_ip($lonid);
12360: my @hosts = &get_hosts_from_ip($ip);
12361: my %iphost = &get_iphost();
12362: my (@idns,%seen);
12363: foreach my $id (@hosts) {
12364: my $dom = &host_domain($id);
12365: my $prim_id = &domain($dom,'primary');
12366: my $prim_ip = &get_host_ip($prim_id);
12367: next if ($seen{$prim_ip});
12368: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12369: foreach my $id (@{$iphost{$prim_ip}}) {
12370: my $intdom = &internet_dom($id);
12371: unless (grep(/^\Q$intdom\E$/,@idns)) {
12372: push(@idns,$intdom);
12373: }
12374: }
12375: }
12376: $seen{$prim_ip} = 1;
12377: }
1.1172.2.23 raeburn 12378: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12379: }
12380:
1.986 foxr 12381: }
12382:
1.1079 raeburn 12383: sub all_loncaparevs {
1.1172.2.39 raeburn 12384: 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 2.11);
1.1079 raeburn 12385: }
12386:
1.1172.2.27 raeburn 12387: # ------------------------------------------------------- Read loncaparev table
12388: {
12389: sub load_loncaparevs {
12390: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12391: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12392: while (my $configline=<$config>) {
12393: chomp($configline);
12394: my ($hostid,$loncaparev)=split(/:/,$configline);
12395: $loncaparevs{$hostid}=$loncaparev;
12396: }
12397: close($config);
12398: }
12399: }
12400: }
12401: }
12402:
12403: # ----------------------------------------------------- Read serverhostID table
12404: {
12405: sub load_serverhomeIDs {
12406: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12407: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12408: while (my $configline=<$config>) {
12409: chomp($configline);
12410: my ($name,$id)=split(/:/,$configline);
12411: $serverhomeIDs{$name}=$id;
12412: }
12413: close($config);
12414: }
12415: }
12416: }
12417: }
12418:
12419:
1.862 albertel 12420: BEGIN {
12421:
12422: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12423: unless ($readit) {
12424: {
12425: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12426: %perlvar = (%perlvar,%{$configvars});
12427: }
12428:
12429:
1.1 albertel 12430: # ------------------------------------------------------ Read spare server file
12431: {
1.448 albertel 12432: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12433:
12434: while (my $configline=<$config>) {
12435: chomp($configline);
1.284 matthew 12436: if ($configline) {
1.784 albertel 12437: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12438: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12439: push(@{ $spareid{$type} }, $host);
1.1 albertel 12440: }
12441: }
1.448 albertel 12442: close($config);
1.1 albertel 12443: }
1.11 www 12444: # ------------------------------------------------------------ Read permissions
12445: {
1.448 albertel 12446: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12447:
12448: while (my $configline=<$config>) {
1.448 albertel 12449: chomp($configline);
12450: if ($configline) {
12451: my ($role,$perm)=split(/ /,$configline);
12452: if ($perm ne '') { $pr{$role}=$perm; }
12453: }
1.11 www 12454: }
1.448 albertel 12455: close($config);
1.11 www 12456: }
12457:
12458: # -------------------------------------------- Read plain texts for permissions
12459: {
1.448 albertel 12460: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12461:
12462: while (my $configline=<$config>) {
1.448 albertel 12463: chomp($configline);
12464: if ($configline) {
1.742 raeburn 12465: my ($short,@plain)=split(/:/,$configline);
12466: %{$prp{$short}} = ();
12467: if (@plain > 0) {
12468: $prp{$short}{'std'} = $plain[0];
12469: for (my $i=1; $i<@plain; $i++) {
12470: $prp{$short}{'alt'.$i} = $plain[$i];
12471: }
12472: }
1.448 albertel 12473: }
1.135 www 12474: }
1.448 albertel 12475: close($config);
1.135 www 12476: }
12477:
12478: # ---------------------------------------------------------- Read package table
12479: {
1.448 albertel 12480: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12481:
12482: while (my $configline=<$config>) {
1.483 albertel 12483: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12484: chomp($configline);
12485: my ($short,$plain)=split(/:/,$configline);
12486: my ($pack,$name)=split(/\&/,$short);
12487: if ($plain ne '') {
12488: $packagetab{$pack.'&'.$name.'&name'}=$name;
12489: $packagetab{$short}=$plain;
12490: }
1.11 www 12491: }
1.448 albertel 12492: close($config);
1.329 matthew 12493: }
12494:
1.1172.2.27 raeburn 12495: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12496:
1.1172.2.27 raeburn 12497: &load_loncaparevs();
12498:
12499: # ------------------------------------------------------- Read serverhostID table
12500:
12501: &load_serverhomeIDs();
1.1074 raeburn 12502:
1.1172.2.27 raeburn 12503: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12504: {
12505: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12506: if (-e $file) {
12507: my $parser = HTML::LCParser->new($file);
12508: while (my $token = $parser->get_token()) {
12509: if ($token->[0] eq 'S') {
12510: my $item = $token->[1];
12511: my $name = $token->[2]{'name'};
12512: my $value = $token->[2]{'value'};
12513: if ($item ne '' && $name ne '' && $value ne '') {
12514: my $release = $parser->get_text();
12515: $release =~ s/(^\s*|\s*$ )//gx;
12516: $needsrelease{$item.':'.$name.':'.$value} = $release;
12517: }
12518: }
12519: }
12520: }
1.1073 raeburn 12521: }
12522:
1.1138 raeburn 12523: # ---------------------------------------------------------- Read managers table
12524: {
12525: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12526: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12527: while (my $configline=<$config>) {
12528: chomp($configline);
12529: next if ($configline =~ /^\#/);
12530: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12531: $managerstab{$configline} = 1;
12532: }
12533: }
12534: close($config);
12535: }
12536: }
12537: }
12538:
1.329 matthew 12539: # ------------- set up temporary directory
12540: {
1.1117 foxr 12541: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12542:
1.11 www 12543: }
12544:
1.794 albertel 12545: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12546: 'compress_threshold'=> 20_000,
12547: });
1.185 www 12548:
1.281 www 12549: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12550: $dumpcount=0;
1.958 www 12551: $locknum=0;
1.22 www 12552:
1.163 harris41 12553: &logtouch();
1.672 albertel 12554: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12555: $readit=1;
1.564 albertel 12556: {
12557: use integer;
12558: my $test=(2**32)+1;
1.568 albertel 12559: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12560: &logthis(" Detected 64bit platform ($_64bit)");
12561: }
1.195 www 12562: }
1.1 albertel 12563: }
1.179 www 12564:
1.1 albertel 12565: 1;
1.191 harris41 12566: __END__
12567:
1.243 albertel 12568: =pod
12569:
1.191 harris41 12570: =head1 NAME
12571:
1.243 albertel 12572: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12573:
12574: =head1 SYNOPSIS
12575:
1.243 albertel 12576: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12577:
12578: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12579:
1.243 albertel 12580: Common parameters:
12581:
12582: =over 4
12583:
12584: =item *
12585:
12586: $uname : an internal username (if $cname expecting a course Id specifically)
12587:
12588: =item *
12589:
12590: $udom : a domain (if $cdom expecting a course's domain specifically)
12591:
12592: =item *
12593:
12594: $symb : a resource instance identifier
12595:
12596: =item *
12597:
12598: $namespace : the name of a .db file that contains the data needed or
12599: being set.
12600:
12601: =back
12602:
1.394 bowersj2 12603: =head1 OVERVIEW
1.191 harris41 12604:
1.394 bowersj2 12605: lonnet provides subroutines which interact with the
12606: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12607: about classes, users, and resources.
1.243 albertel 12608:
12609: For many of these objects you can also use this to store data about
12610: them or modify them in various ways.
1.191 harris41 12611:
1.394 bowersj2 12612: =head2 Symbs
1.191 harris41 12613:
1.394 bowersj2 12614: To identify a specific instance of a resource, LON-CAPA uses symbols
12615: or "symbs"X<symb>. These identifiers are built from the URL of the
12616: map, the resource number of the resource in the map, and the URL of
12617: the resource itself. The latter is somewhat redundant, but might help
12618: if maps change.
12619:
12620: An example is
12621:
12622: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12623:
12624: The respective map entry is
12625:
12626: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12627: title="Problem 2">
12628: </resource>
12629:
12630: Symbs are used by the random number generator, as well as to store and
12631: restore data specific to a certain instance of for example a problem.
12632:
12633: =head2 Storing And Retrieving Data
12634:
12635: X<store()>X<cstore()>X<restore()>Three of the most important functions
12636: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12637: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12638: is is the non-critical message twin of cstore. These functions are for
12639: handlers to store a perl hash to a user's permanent data space in an
12640: easy manner, and to retrieve it again on another call. It is expected
12641: that a handler would use this once at the beginning to retrieve data,
12642: and then again once at the end to send only the new data back.
12643:
12644: The data is stored in the user's data directory on the user's
12645: homeserver under the ID of the course.
12646:
12647: The hash that is returned by restore will have all of the previous
12648: value for all of the elements of the hash.
12649:
12650: Example:
12651:
12652: #creating a hash
12653: my %hash;
12654: $hash{'foo'}='bar';
12655:
12656: #storing it
12657: &Apache::lonnet::cstore(\%hash);
12658:
12659: #changing a value
12660: $hash{'foo'}='notbar';
12661:
12662: #adding a new value
12663: $hash{'bar'}='foo';
12664: &Apache::lonnet::cstore(\%hash);
12665:
12666: #retrieving the hash
12667: my %history=&Apache::lonnet::restore();
12668:
12669: #print the hash
12670: foreach my $key (sort(keys(%history))) {
12671: print("\%history{$key} = $history{$key}");
12672: }
12673:
12674: Will print out:
1.191 harris41 12675:
1.394 bowersj2 12676: %history{1:foo} = bar
12677: %history{1:keys} = foo:timestamp
12678: %history{1:timestamp} = 990455579
12679: %history{2:bar} = foo
12680: %history{2:foo} = notbar
12681: %history{2:keys} = foo:bar:timestamp
12682: %history{2:timestamp} = 990455580
12683: %history{bar} = foo
12684: %history{foo} = notbar
12685: %history{timestamp} = 990455580
12686: %history{version} = 2
12687:
12688: Note that the special hash entries C<keys>, C<version> and
12689: C<timestamp> were added to the hash. C<version> will be equal to the
12690: total number of versions of the data that have been stored. The
12691: C<timestamp> attribute will be the UNIX time the hash was
12692: stored. C<keys> is available in every historical section to list which
12693: keys were added or changed at a specific historical revision of a
12694: hash.
12695:
12696: B<Warning>: do not store the hash that restore returns directly. This
12697: will cause a mess since it will restore the historical keys as if the
12698: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12699:
1.394 bowersj2 12700: Calling convention:
1.191 harris41 12701:
1.1172.2.27 raeburn 12702: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12703: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12704:
1.394 bowersj2 12705: For more detailed information, see lonnet specific documentation.
1.191 harris41 12706:
1.394 bowersj2 12707: =head1 RETURN MESSAGES
1.191 harris41 12708:
1.394 bowersj2 12709: =over 4
1.191 harris41 12710:
1.394 bowersj2 12711: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12712:
1.394 bowersj2 12713: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12714: when the connection is brought back up
1.191 harris41 12715:
1.394 bowersj2 12716: =item * B<con_failed>: unable to contact remote host and unable to save message
12717: for later delivery
1.191 harris41 12718:
1.967 bisitz 12719: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12720:
1.394 bowersj2 12721: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12722: that was requested
1.191 harris41 12723:
1.243 albertel 12724: =back
1.191 harris41 12725:
1.243 albertel 12726: =head1 PUBLIC SUBROUTINES
1.191 harris41 12727:
1.243 albertel 12728: =head2 Session Environment Functions
1.191 harris41 12729:
1.243 albertel 12730: =over 4
1.191 harris41 12731:
1.394 bowersj2 12732: =item *
12733: X<appenv()>
1.949 raeburn 12734: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12735: the user envirnoment file, and will be restored for each access this
1.620 albertel 12736: user makes during this session, also modifies the %env for the current
1.949 raeburn 12737: process. Optional rolesarrayref - if defined contains a reference to an array
12738: of roles which are exempt from the restriction on modifying user.role entries
12739: in the user's environment.db and in %env.
1.191 harris41 12740:
12741: =item *
1.394 bowersj2 12742: X<delenv()>
1.987 raeburn 12743: B<delenv($delthis,$regexp)>: removes all items from the session
12744: environment file that begin with $delthis. If the
12745: optional second arg - $regexp - is true, $delthis is treated as a
12746: regular expression, otherwise \Q$delthis\E is used.
12747: The values are also deleted from the current processes %env.
1.191 harris41 12748:
1.795 albertel 12749: =item * get_env_multiple($name)
12750:
12751: gets $name from the %env hash, it seemlessly handles the cases where multiple
12752: values may be defined and end up as an array ref.
12753:
12754: returns an array of values
12755:
1.243 albertel 12756: =back
12757:
12758: =head2 User Information
1.191 harris41 12759:
1.243 albertel 12760: =over 4
1.191 harris41 12761:
12762: =item *
1.394 bowersj2 12763: X<queryauthenticate()>
12764: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12765: authentication scheme
12766:
12767: =item *
1.394 bowersj2 12768: X<authenticate()>
1.1073 raeburn 12769: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12770: authenticate user from domain's lib servers (first use the current
12771: one). C<$upass> should be the users password.
1.1073 raeburn 12772: $checkdefauth is optional (value is 1 if a check should be made to
12773: authenticate user using default authentication method, and allow
12774: account creation if username does not have account in the domain).
12775: $clientcancheckhost is optional (value is 1 if checking whether the
12776: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12777:
12778: =item *
1.394 bowersj2 12779: X<homeserver()>
12780: B<homeserver($uname,$udom)>: find the server which has
12781: the user's directory and files (there must be only one), this caches
12782: the answer, and also caches if there is a borken connection.
1.191 harris41 12783:
12784: =item *
1.394 bowersj2 12785: X<idget()>
12786: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12787: (IDs are a unique resource in a domain, there must be only 1 ID per
12788: username, and only 1 username per ID in a specific domain) (returns
12789: hash: id=>name,id=>name)
1.191 harris41 12790:
12791: =item *
1.394 bowersj2 12792: X<idrget()>
12793: B<idrget($udom,@unames)>: find the IDs behind a list of
12794: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12795:
12796: =item *
1.394 bowersj2 12797: X<idput()>
12798: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12799:
12800: =item *
1.394 bowersj2 12801: X<rolesinit()>
1.1169 droeschl 12802: B<rolesinit($udom,$username)>: get user privileges.
12803: returns user role, first access and timer interval hashes
1.243 albertel 12804:
12805: =item *
1.1171 droeschl 12806: X<privileged()>
12807: B<privileged($username,$domain)>: returns a true if user has a
12808: privileged and active role (i.e. su or dc), false otherwise.
12809:
12810: =item *
1.551 albertel 12811: X<getsection()>
12812: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12813: course $cname, return section name/number or '' for "not in course"
12814: and '-1' for "no section"
12815:
12816: =item *
1.394 bowersj2 12817: X<userenvironment()>
12818: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12819: passed in @what from the requested user's environment, returns a hash
12820:
1.858 raeburn 12821: =item *
12822: X<userlog_query()>
1.859 albertel 12823: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12824: activity.log file. %filters defines filters applied when parsing the
12825: log file. These can be start or end timestamps, or the type of action
12826: - log to look for Login or Logout events, check for Checkin or
12827: Checkout, role for role selection. The response is in the form
12828: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12829: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12830:
1.243 albertel 12831: =back
12832:
12833: =head2 User Roles
12834:
12835: =over 4
12836:
12837: =item *
12838:
1.810 raeburn 12839: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12840: F: full access
12841: U,I,K: authentication modes (cxx only)
12842: '': forbidden
12843: 1: user needs to choose course
12844: 2: browse allowed
1.766 albertel 12845: A: passphrase authentication needed
1.243 albertel 12846:
12847: =item *
12848:
1.1172.2.13 raeburn 12849: constructaccess($url,$setpriv) : check for access to construction space URL
12850:
12851: See if the owner domain and name in the URL match those in the
12852: expected environment. If so, return three element list
12853: ($ownername,$ownerdomain,$ownerhome).
12854:
12855: Otherwise return the null string.
12856:
12857: If second argument 'setpriv' is true, it assigns the privileges,
12858: and returns the same three element list, unless the owner has
12859: blocked "ad hoc" Domain Coordinator access to the Author Space,
12860: in which case the null string is returned.
12861:
12862: =item *
12863:
1.243 albertel 12864: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12865: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12866: and course level
12867:
12868: =item *
12869:
1.988 raeburn 12870: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12871: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12872: $type is Course (default) or Community.
1.988 raeburn 12873: If $forcedefault evaluates to true, text returned will be default
12874: text for $type. Otherwise, if this is a course, the text returned
12875: will be a custom name for the role (if defined in the course's
12876: environment). If no custom name is defined the default is returned.
12877:
1.832 raeburn 12878: =item *
12879:
1.1172.2.23 raeburn 12880: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12881: All arguments are optional. Returns a hash of a roles, either for
12882: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12883: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12884: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12885: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12886: For each key, value is set to colon-separated start and end times for
12887: the role. If no username and domain are specified, will default to
1.934 raeburn 12888: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12889: of role statuses (active, future or previous), roles
12890: (e.g., cc,in, st etc.) and domains of the roles which can be used
12891: to restrict the list of roles reported. If no array ref is
12892: provided for types, will default to return only active roles.
1.834 albertel 12893:
1.1172.2.13 raeburn 12894: =item *
12895:
12896: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12897: user: $uname:$udom has a role in the course: $cdom_$cnum.
12898:
12899: Additional optional arguments are: $type (if role checking is to be restricted
12900: to certain user status types -- previous (expired roles), active (currently
12901: available roles) or future (roles available in the future), and
12902: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12903: have active Domain Coordinator role in course's domain or in additional
12904: domains (specified in 'Domains to check for privileged users' in course
12905: environment -- set via: Course Settings -> Classlists and staff listing).
12906:
12907: =item *
12908:
12909: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12910: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12911: $possdomains and $possroles are optional array refs -- to domains to check and
12912: roles to check. If $possdomains is not specified, a dump will be done of the
12913: users' roles.db to check for a dc or su role in any domain. This can be
12914: time consuming if &privileged is called repeatedly (e.g., when displaying a
12915: classlist), so in such cases, supplying a $possdomains array is preferred, as
12916: this then allows &privileged_by_domain() to be used, which caches the identity
12917: of privileged users, eliminating the need for repeated calls to &dump().
12918:
12919: =item *
12920:
12921: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12922: where the outer hash keys are domains specified in the $possdomains array ref,
12923: next inner hash keys are privileged roles specified in the $roles array ref,
12924: and the innermost hash contains key = value pairs for username:domain = end:start
12925: for active or future "privileged" users with that role in that domain. To avoid
12926: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12927: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12928:
1.243 albertel 12929: =back
12930:
12931: =head2 User Modification
12932:
12933: =over 4
12934:
12935: =item *
12936:
1.957 raeburn 12937: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12938: user for the level given by URL. Optional start and end dates (leave empty
12939: string or zero for "no date")
1.191 harris41 12940:
12941: =item *
12942:
1.243 albertel 12943: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12944: change a users, password, possible return values are: ok,
12945: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12946: refused
1.191 harris41 12947:
12948: =item *
12949:
1.243 albertel 12950: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12951:
12952: =item *
12953:
1.1058 raeburn 12954: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12955: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12956:
12957: will update user information (firstname,middlename,lastname,generation,
12958: permanentemail), and if forceid is true, student/employee ID also.
12959: A user's institutional affiliation(s) can also be updated.
12960: User information fields will not be overwritten with empty entries
12961: unless the field is included in the $candelete array reference.
12962: This array is included when a single user is modified via "Manage Users",
12963: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12964:
12965: =item *
12966:
1.286 matthew 12967: modifystudent
12968:
1.957 raeburn 12969: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12970: The course id is resolved based on the current user's environment.
12971: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12972: associated with a course.
12973:
1.297 matthew 12974: This call is essentially a wrapper for lonnet::modifyuser and
12975: lonnet::modify_student_enrollment
1.286 matthew 12976:
12977: Inputs:
12978:
12979: =over 4
12980:
1.957 raeburn 12981: =item B<$udom> Student's loncapa domain
1.286 matthew 12982:
1.957 raeburn 12983: =item B<$uname> Student's loncapa login name
1.286 matthew 12984:
1.964 bisitz 12985: =item B<$uid> Student/Employee ID
1.286 matthew 12986:
1.957 raeburn 12987: =item B<$umode> Student's authentication mode
1.286 matthew 12988:
1.957 raeburn 12989: =item B<$upass> Student's password
1.286 matthew 12990:
1.957 raeburn 12991: =item B<$first> Student's first name
1.286 matthew 12992:
1.957 raeburn 12993: =item B<$middle> Student's middle name
1.286 matthew 12994:
1.957 raeburn 12995: =item B<$last> Student's last name
1.286 matthew 12996:
1.957 raeburn 12997: =item B<$gene> Student's generation
1.286 matthew 12998:
1.957 raeburn 12999: =item B<$usec> Student's section in course
1.286 matthew 13000:
13001: =item B<$end> Unix time of the roles expiration
13002:
13003: =item B<$start> Unix time of the roles start date
13004:
13005: =item B<$forceid> If defined, allow $uid to be changed
13006:
13007: =item B<$desiredhome> server to use as home server for student
13008:
1.957 raeburn 13009: =item B<$email> Student's permanent e-mail address
13010:
13011: =item B<$type> Type of enrollment (auto or manual)
13012:
1.963 raeburn 13013: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13014:
13015: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13016:
1.963 raeburn 13017: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13018:
1.963 raeburn 13019: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13020:
1.1172.2.19 raeburn 13021: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13022:
13023: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957 raeburn 13024:
1.286 matthew 13025: =back
1.297 matthew 13026:
13027: =item *
13028:
13029: modify_student_enrollment
13030:
1.1172.2.31 raeburn 13031: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13032: 'role.request.course' must be defined for this function to proceed.
13033:
13034: Inputs:
13035:
13036: =over 4
13037:
1.1172.2.31 raeburn 13038: =item $udom, student's domain
1.297 matthew 13039:
1.1172.2.31 raeburn 13040: =item $uname, student's name
1.297 matthew 13041:
1.1172.2.31 raeburn 13042: =item $uid, student's user id
1.297 matthew 13043:
1.1172.2.31 raeburn 13044: =item $first, student's first name
1.297 matthew 13045:
13046: =item $middle
13047:
13048: =item $last
13049:
13050: =item $gene
13051:
13052: =item $usec
13053:
13054: =item $end
13055:
13056: =item $start
13057:
1.957 raeburn 13058: =item $type
13059:
13060: =item $locktype
13061:
13062: =item $cid
13063:
13064: =item $selfenroll
13065:
13066: =item $context
13067:
1.1172.2.19 raeburn 13068: =item $credits, number of credits student will earn from this class
13069:
1.297 matthew 13070: =back
13071:
1.191 harris41 13072:
13073: =item *
13074:
1.243 albertel 13075: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13076: custom role; give a custom role to a user for the level given by URL. Specify
13077: name and domain of role author, and role name
1.191 harris41 13078:
13079: =item *
13080:
1.243 albertel 13081: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13082:
13083: =item *
13084:
1.243 albertel 13085: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13086:
13087: =back
13088:
13089: =head2 Course Infomation
13090:
13091: =over 4
1.191 harris41 13092:
13093: =item *
13094:
1.1118 foxr 13095: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13096: specified course id, including all environment settings for the
13097: course, the description of the course will be in the hash under the
13098: key 'description'
1.191 harris41 13099:
1.1118 foxr 13100: $options is an optional parameter that if supplied is a hash reference that controls
13101: what how this function works. It has the following key/values:
13102:
13103: =over 4
13104:
13105: =item freshen_cache
13106:
13107: If defined, and the environment cache for the course is valid, it is
13108: returned in the returned hash.
13109:
13110: =item one_time
13111:
13112: If defined, the last cache time is set to _now_
13113:
13114: =item user
13115:
13116: If defined, the supplied username is used instead of the current user.
13117:
13118:
13119: =back
13120:
1.191 harris41 13121: =item *
13122:
1.624 albertel 13123: resdata($name,$domain,$type,@which) : request for current parameter
13124: setting for a specific $type, where $type is either 'course' or 'user',
13125: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13126: answers for 10 minutes.
1.243 albertel 13127:
1.877 foxr 13128: =item *
13129:
13130: get_courseresdata($courseid, $domain) : dump the entire course resource
13131: data base, returning a hash that is keyed by the resource name and has
13132: values that are the resource value. I believe that the timestamps and
13133: versions are also returned.
13134:
1.1172.2.31 raeburn 13135: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13136: supplemental content area. This routine caches the number of files for
13137: 10 minutes.
13138:
1.243 albertel 13139: =back
13140:
13141: =head2 Course Modification
13142:
13143: =over 4
1.191 harris41 13144:
13145: =item *
13146:
1.243 albertel 13147: writecoursepref($courseid,%prefs) : write preferences (environment
13148: database) for a course
1.191 harris41 13149:
13150: =item *
13151:
1.1011 raeburn 13152: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13153:
13154: =item *
13155:
1.1038 raeburn 13156: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13157:
1.1167 droeschl 13158: =item *
13159:
13160: is_course($courseid), is_course($cdom, $cnum)
13161:
13162: Accepts either a combined $courseid (in the form of domain_courseid) or the
13163: two component version $cdom, $cnum. It checks if the specified course exists.
13164:
13165: Returns:
13166: undef if the course doesn't exist, otherwise
13167: in scalar context the combined courseid.
13168: in list context the two components of the course identifier, domain and
13169: courseid.
13170:
1.243 albertel 13171: =back
13172:
13173: =head2 Resource Subroutines
13174:
13175: =over 4
1.191 harris41 13176:
13177: =item *
13178:
1.243 albertel 13179: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13180:
13181: =item *
13182:
1.243 albertel 13183: repcopy($filename) : subscribes to the requested file, and attempts to
13184: replicate from the owning library server, Might return
1.607 raeburn 13185: 'unavailable', 'not_found', 'forbidden', 'ok', or
13186: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13187: resource. Expects the local filesystem pathname
13188: (/home/httpd/html/res/....)
13189:
13190: =back
13191:
13192: =head2 Resource Information
13193:
13194: =over 4
1.191 harris41 13195:
13196: =item *
13197:
1.1172.2.28 raeburn 13198: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13199: and returns the value of a variety of different possible values,
13200: $varname should be a request string, and the other parameters can be
13201: used to specify who and what one is asking about. Ordinarily, $cid
13202: does not need to be specified, as it is retrived from
13203: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13204: within lonuserstate::loadmap() when initializing a course, before
13205: $env{'request.course.id'} has been set, so it needs to be provided
13206: in that one case.
1.243 albertel 13207:
13208: Possible values for $varname are environment.lastname (or other item
13209: from the envirnment hash), user.name (or someother aspect about the
13210: user), resource.0.maxtries (or some other part and parameter of a
13211: resource)
1.204 albertel 13212:
13213: =item *
13214:
1.243 albertel 13215: directcondval($number) : get current value of a condition; reads from a state
13216: string
1.204 albertel 13217:
13218: =item *
13219:
1.243 albertel 13220: condval($condidx) : value of condition index based on state
1.204 albertel 13221:
13222: =item *
13223:
1.243 albertel 13224: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13225: resource's metadata, $what should be either a specific key, or either
13226: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13227: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13228:
13229: this function automatically caches all requests
1.191 harris41 13230:
13231: =item *
13232:
1.243 albertel 13233: metadata_query($query,$custom,$customshow) : make a metadata query against the
13234: network of library servers; returns file handle of where SQL and regex results
13235: will be stored for query
1.191 harris41 13236:
13237: =item *
13238:
1.243 albertel 13239: symbread($filename) : return symbolic list entry (filename argument optional);
13240: returns the data handle
1.191 harris41 13241:
13242: =item *
13243:
1.1172.2.17 raeburn 13244: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13245: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13246: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13247: on failure, user must be in a course, as it assumes the existence of
13248: the course initial hash, and uses $env('request.course.id'}. The third
13249: arg is an optional reference to a scalar. If this arg is passed in the
13250: call to symbverify, it will be set to 1 if the symb has been set to be
13251: encrypted; otherwise it will be null.
1.243 albertel 13252:
1.191 harris41 13253: =item *
13254:
1.243 albertel 13255: symbclean($symb) : removes versions numbers from a symb, returns the
13256: cleaned symb
1.191 harris41 13257:
13258: =item *
13259:
1.243 albertel 13260: is_on_map($uri) : checks if the $uri is somewhere on the current
13261: course map, user must be in a course for it to work.
1.191 harris41 13262:
13263: =item *
13264:
1.243 albertel 13265: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13266:
13267: =item *
13268:
1.243 albertel 13269: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13270: a random seed, all arguments are optional, if they aren't sent it uses the
13271: environment to derive them. Note: if symb isn't sent and it can't get one
13272: from &symbread it will use the current time as its return value
1.191 harris41 13273:
13274: =item *
13275:
1.243 albertel 13276: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13277: unfakeable, receipt
1.191 harris41 13278:
13279: =item *
13280:
1.620 albertel 13281: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13282:
13283: =item *
13284:
1.243 albertel 13285: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13286:
13287: =item *
13288:
1.243 albertel 13289: 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 13290:
13291: =item *
13292:
1.243 albertel 13293: 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 13294:
13295: =item *
13296:
1.243 albertel 13297: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13298:
13299: =item *
13300:
1.243 albertel 13301: devalidate($symb) : devalidate temporary spreadsheet calculations,
13302: forcing spreadsheet to reevaluate the resource scores next time.
13303:
1.1172.2.13 raeburn 13304: =item *
13305:
13306: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13307: when viewing in course context.
13308:
13309: input: six args -- filename (decluttered), course number, course domain,
13310: url, symb (if registered) and group (if this is a
13311: group item -- e.g., bulletin board, group page etc.).
13312:
13313: output: array of five scalars --
13314: $cfile -- url for file editing if editable on current server
13315: $home -- homeserver of resource (i.e., for author if published,
13316: or course if uploaded.).
13317: $switchserver -- 1 if server switch will be needed.
13318: $forceedit -- 1 if icon/link should be to go to edit mode
13319: $forceview -- 1 if icon/link should be to go to view mode
13320:
13321: =item *
13322:
13323: is_course_upload($file,$cnum,$cdom)
13324:
13325: Used in course context to determine if current file was uploaded to
13326: the course (i.e., would be found in /userfiles/docs on the course's
13327: homeserver.
13328:
13329: input: 3 args -- filename (decluttered), course number and course domain.
13330: output: boolean -- 1 if file was uploaded.
13331:
1.243 albertel 13332: =back
13333:
13334: =head2 Storing/Retreiving Data
13335:
13336: =over 4
1.191 harris41 13337:
13338: =item *
13339:
1.243 albertel 13340: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13341: for this url; hashref needs to be given and should be a \%hashname; the
13342: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13343: be derived from the env
1.191 harris41 13344:
13345: =item *
13346:
1.243 albertel 13347: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13348: uses critical subroutine
1.191 harris41 13349:
13350: =item *
13351:
1.243 albertel 13352: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13353: all args are optional
1.191 harris41 13354:
13355: =item *
13356:
1.717 albertel 13357: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13358: dumps the complete (or key matching regexp) namespace into a hash
13359: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13360: normally &store()ed into
13361:
13362: $range should be either an integer '100' (give me the first 100
13363: matching records)
13364: or be two integers sperated by a - with no spaces
13365: '30-50' (give me the 30th through the 50th matching
13366: records)
13367:
13368:
13369: =item *
13370:
1.1172.2.59 raeburn 13371: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13372: replaces a &store() version of data with a replacement set of data
13373: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13374: reference. If $tolog is true, the transaction is logged in the courselog
13375: with an action=PUTSTORE.
1.717 albertel 13376:
13377: =item *
13378:
1.243 albertel 13379: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13380: works very similar to store/cstore, but all data is stored in a
13381: temporary location and can be reset using tmpreset, $storehash should
13382: be a hash reference, returns nothing on success
1.191 harris41 13383:
13384: =item *
13385:
1.243 albertel 13386: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13387: similar to restore, but all data is stored in a temporary location and
13388: can be reset using tmpreset. Returns a hash of values on success,
13389: error string otherwise.
1.191 harris41 13390:
13391: =item *
13392:
1.243 albertel 13393: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13394: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13395:
13396: =item *
13397:
1.243 albertel 13398: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13399: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13400:
13401: =item *
13402:
1.243 albertel 13403: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13404: namesp ($udom and $uname are optional)
1.191 harris41 13405:
13406: =item *
13407:
1.702 albertel 13408: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13409: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13410: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13411:
1.702 albertel 13412: $range should be either an integer '100' (give me the first 100
13413: matching records)
13414: or be two integers sperated by a - with no spaces
13415: '30-50' (give me the 30th through the 50th matching
13416: records)
1.449 matthew 13417: =item *
13418:
13419: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13420: $store can be a scalar, an array reference, or if the amount to be
13421: incremented is > 1, a hash reference.
13422:
13423: ($udom and $uname are optional)
1.191 harris41 13424:
13425: =item *
13426:
1.243 albertel 13427: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13428: ($udom and $uname are optional)
1.191 harris41 13429:
13430: =item *
13431:
1.243 albertel 13432: cput($namespace,$storehash,$udom,$uname) : critical put
13433: ($udom and $uname are optional)
1.191 harris41 13434:
13435: =item *
13436:
1.748 albertel 13437: newput($namespace,$storehash,$udom,$uname) :
13438:
13439: Attempts to store the items in the $storehash, but only if they don't
13440: currently exist, if this succeeds you can be certain that you have
13441: successfully created a new key value pair in the $namespace db.
13442:
13443:
13444: Args:
13445: $namespace: name of database to store values to
13446: $storehash: hashref to store to the db
13447: $udom: (optional) domain of user containing the db
13448: $uname: (optional) name of user caontaining the db
13449:
13450: Returns:
13451: 'ok' -> succeeded in storing all keys of $storehash
13452: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13453: least <key> already existed in the db (other
13454: requested keys may also already exist)
1.967 bisitz 13455: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13456: 'con_lost' -> unable to contact request server
13457: 'refused' -> action was not allowed by remote machine
13458:
13459:
13460: =item *
13461:
1.243 albertel 13462: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13463: reference filled in from namesp (encrypts the return communication)
13464: ($udom and $uname are optional)
1.191 harris41 13465:
13466: =item *
13467:
1.243 albertel 13468: log($udom,$name,$home,$message) : write to permanent log for user; use
13469: critical subroutine
13470:
1.806 raeburn 13471: =item *
13472:
1.860 raeburn 13473: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13474: array reference filled in from namespace found in domain level on either
13475: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13476:
13477: =item *
13478:
1.860 raeburn 13479: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13480: domain level either on specified domain server ($uhome) or primary domain
13481: server ($udom and $uhome are optional)
1.806 raeburn 13482:
1.943 raeburn 13483: =item *
13484:
1.1172.2.35 raeburn 13485: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13486: for: authentication, language, quotas, timezone, date locale, and portal URL in
13487: the target domain.
13488:
13489: May also include additional key => value pairs for the following groups:
13490:
13491: =over
13492:
13493: =item
13494: disk quotas (MB allocated by default to portfolios and authoring spaces).
13495:
13496: =over
13497:
13498: =item defaultquota, authorquota
13499:
13500: =back
13501:
13502: =item
13503: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13504: portfolio for users).
13505:
13506: =over
13507:
13508: =item
13509: aboutme, blog, webdav, portfolio
13510:
13511: =back
13512:
13513: =item
13514: requestcourses: ability to request courses, and how requests are processed.
13515:
13516: =over
13517:
13518: =item
1.1172.2.37 raeburn 13519: official, unofficial, community, textbook
1.1172.2.35 raeburn 13520:
13521: =back
13522:
13523: =item
13524: inststatus: types of institutional affiliation, and order in which they are displayed.
13525:
13526: =over
13527:
13528: =item
1.1172.2.44 raeburn 13529: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13530:
13531: =back
13532:
13533: =item
13534: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13535: for course's uploaded content.
13536:
13537: =over
13538:
13539: =item
1.1172.2.37 raeburn 13540: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13541:
13542: =back
13543:
13544: =item
13545: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13546: on your servers.
13547:
13548: =over
13549:
13550: =item
13551: remotesessions, hostedsessions
13552:
13553: =back
13554:
13555: =back
13556:
13557: In cases where a domain coordinator has never used the "Set Domain Configuration"
13558: utility to create a configuration.db file on a domain's primary library server
13559: only the following domain defaults: auth_def, auth_arg_def, lang_def
13560: -- corresponding values are authentication type (internal, krb4, krb5,
13561: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13562: will be available. Values are retrieved from cache (if current), unless the
13563: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13564: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13565:
13566: Typical usage:
1.943 raeburn 13567:
1.1172.2.35 raeburn 13568: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13569:
1.243 albertel 13570: =back
13571:
13572: =head2 Network Status Functions
13573:
13574: =over 4
1.191 harris41 13575:
13576: =item *
13577:
1.1137 raeburn 13578: dirlist() : return directory list based on URI (first arg).
13579:
13580: Inputs: 1 required, 5 optional.
13581:
13582: =over
13583:
13584: =item
13585: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13586:
13587: =item
13588: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13589:
13590: =item
13591: $username - username of user/course to be listed. Extracted from $uri if absent.
13592:
13593: =item
13594: $getpropath - boolean: 1 if prepend path using &propath().
13595:
13596: =item
13597: $getuserdir - boolean: 1 if prepend path for "userfiles".
13598:
13599: =item
13600: $alternateRoot - path to prepend in place of path from $uri.
13601:
13602: =back
13603:
13604: Returns: Array of up to two items.
13605:
13606: =over
13607:
13608: a reference to an array of files/subdirectories
13609:
13610: =over
13611:
13612: Each element in the array of files/subdirectories is a & separated list of
13613: item name and the result of running stat on the item. If dirlist was requested
13614: for a file instead of a directory, the item name will be ''. For a directory
13615: listing, if the item is a metadata file, the element will end &N&M
13616: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13617: default copyright set (1).
13618:
13619: =back
13620:
13621: a scalar containing error condition (if encountered).
13622:
13623: =over
13624:
13625: =item
13626: no_host (no homeserver identified for $username:$domain).
13627:
13628: =item
13629: no_such_host (server contacted for listing not identified as valid host).
13630:
13631: =item
13632: con_lost (connection to remote server failed).
13633:
13634: =item
13635: refused (invalid $username:$domain received on lond side).
13636:
13637: =item
13638: no_such_dir (directory at specified path on lond side does not exist).
13639:
13640: =item
13641: empty (directory at specified path on lond side is empty).
13642:
13643: =over
13644:
13645: This is currently not encountered because the &ls3, &ls2,
13646: &ls (_handler) routines on the lond side do not filter out
13647: . and .. from a directory listing.
13648:
13649: =back
13650:
13651: =back
13652:
13653: =back
1.191 harris41 13654:
13655: =item *
13656:
1.243 albertel 13657: spareserver() : find server with least workload from spare.tab
13658:
1.986 foxr 13659:
13660: =item *
13661:
13662: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13663: if there is no corresponding loncapa host.
13664:
1.243 albertel 13665: =back
13666:
1.986 foxr 13667:
1.243 albertel 13668: =head2 Apache Request
13669:
13670: =over 4
1.191 harris41 13671:
13672: =item *
13673:
1.243 albertel 13674: ssi($url,%hash) : server side include, does a complete request cycle on url to
13675: localhost, posts hash
13676:
13677: =back
13678:
13679: =head2 Data to String to Data
13680:
13681: =over 4
1.191 harris41 13682:
13683: =item *
13684:
1.243 albertel 13685: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13686: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13687:
13688: =item *
13689:
1.243 albertel 13690: hashref2str($hashref) : convert a hashref into a string complete with
13691: escaping and '=' and '&' separators, supports elements that are
13692: arrayrefs and hashrefs
1.191 harris41 13693:
13694: =item *
13695:
1.243 albertel 13696: arrayref2str($arrayref) : convert an arrayref into a string complete
13697: with escaping and '&' separators, supports elements that are arrayrefs
13698: and hashrefs
1.191 harris41 13699:
13700: =item *
13701:
1.243 albertel 13702: str2hash($string) : convert string to hash using unescaping and
13703: splitting on '=' and '&', supports elements that are arrayrefs and
13704: hashrefs
1.191 harris41 13705:
13706: =item *
13707:
1.243 albertel 13708: str2array($string) : convert string to hash using unescaping and
13709: splitting on '&', supports elements that are arrayrefs and hashrefs
13710:
13711: =back
13712:
13713: =head2 Logging Routines
13714:
13715:
13716: These routines allow one to make log messages in the lonnet.log and
13717: lonnet.perm logfiles.
1.191 harris41 13718:
1.1119 foxr 13719: =over 4
13720:
1.191 harris41 13721: =item *
13722:
1.243 albertel 13723: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13724:
13725: =item *
13726:
1.243 albertel 13727: logthis() : append message to the normal lonnet.log file, it gets
13728: preiodically rolled over and deleted.
1.191 harris41 13729:
13730: =item *
13731:
1.243 albertel 13732: logperm() : append a permanent message to lonnet.perm.log, this log
13733: file never gets deleted by any automated portion of the system, only
13734: messages of critical importance should go in here.
13735:
1.1119 foxr 13736:
1.243 albertel 13737: =back
13738:
13739: =head2 General File Helper Routines
13740:
13741: =over 4
1.191 harris41 13742:
13743: =item *
13744:
1.481 raeburn 13745: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13746: (a) files in /uploaded
13747: (i) If a local copy of the file exists -
13748: compares modification date of local copy with last-modified date for
13749: definitive version stored on home server for course. If local copy is
13750: stale, requests a new version from the home server and stores it.
13751: If the original has been removed from the home server, then local copy
13752: is unlinked.
13753: (ii) If local copy does not exist -
13754: requests the file from the home server and stores it.
13755:
13756: If $caller is 'uploadrep':
13757: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13758: for request for files originally uploaded via DOCS.
13759: - returns 'ok' if fresh local copy now available, -1 otherwise.
13760:
13761: Otherwise:
13762: This indicates a call from the content generation phase of the request.
13763: - returns the entire contents of the file or -1.
13764:
13765: (b) files in /res
13766: - returns the entire contents of a file or -1;
13767: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13768:
1.712 albertel 13769:
13770: =item *
13771:
13772: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13773: reference
13774:
13775: returns either a stat() list of data about the file or an empty list
13776: if the file doesn't exist or couldn't find out about it (connection
13777: problems or user unknown)
13778:
1.191 harris41 13779: =item *
13780:
1.243 albertel 13781: filelocation($dir,$file) : returns file system location of a file
13782: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13783: directory that relative $file lookups are to looked in ($dir of /a/dir
13784: and a file of ../bob will become /a/bob)
1.191 harris41 13785:
13786: =item *
13787:
13788: hreflocation($dir,$file) : returns file system location or a URL; same as
13789: filelocation except for hrefs
13790:
13791: =item *
13792:
1.1172.2.49 raeburn 13793: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13794: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13795:
1.243 albertel 13796: =back
13797:
1.608 albertel 13798: =head2 Usererfile file routines (/uploaded*)
13799:
13800: =over 4
13801:
13802: =item *
13803:
13804: userfileupload(): main rotine for putting a file in a user or course's
13805: filespace, arguments are,
13806:
1.620 albertel 13807: formname - required - this is the name of the element in $env where the
1.608 albertel 13808: filename, and the contents of the file to create/modifed exist
1.620 albertel 13809: the filename is in $env{'form.'.$formname.'.filename'} and the
13810: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13811: context - if coursedoc, store the file in the course of the active role
13812: of the current user;
13813: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13814: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13815: subdir - required - subdirectory to put the file in under ../userfiles/
13816: if undefined, it will be placed in "unknown"
13817:
13818: (This routine calls clean_filename() to remove any dangerous
13819: characters from the filename, and then calls finuserfileupload() to
13820: complete the transaction)
13821:
13822: returns either the url of the uploaded file (/uploaded/....) if successful
13823: and /adm/notfound.html if unsuccessful
13824:
13825: =item *
13826:
13827: clean_filename(): routine for cleaing a filename up for storage in
13828: userfile space, argument is:
13829:
13830: filename - proposed filename
13831:
13832: returns: the new clean filename
13833:
13834: =item *
13835:
1.1090 raeburn 13836: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13837: userspace, probably shouldn't be called directly
13838:
13839: docuname: username or courseid of destination for the file
13840: docudom: domain of user/course of destination for the file
13841: formname: same as for userfileupload()
1.1090 raeburn 13842: fname: filename (including subdirectories) for the file
13843: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13844: allfiles: reference to hash used to store objects found by parser
13845: codebase: reference to hash used for codebases of java objects found by parser
13846: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13847: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13848: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13849: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13850: context: if 'overwrite', will move the uploaded file from its temporary location to
13851: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13852: mimetype: reference to scalar to accommodate mime type determined
13853: from File::MMagic if $parser = parse.
1.608 albertel 13854:
13855: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13856: and /adm/notfound.html if unsuccessful (or an error message if context
13857: was 'overwrite').
13858:
1.608 albertel 13859:
13860: =item *
13861:
13862: renameuserfile(): renames an existing userfile to a new name
13863:
13864: Args:
13865: docuname: username or courseid of destination for the file
13866: docudom: domain of user/course of destination for the file
13867: old: current file name (including any subdirs under userfiles)
13868: new: desired file name (including any subdirs under userfiles)
13869:
13870: =item *
13871:
13872: mkdiruserfile(): creates a directory is a userfiles dir
13873:
13874: Args:
13875: docuname: username or courseid of destination for the file
13876: docudom: domain of user/course of destination for the file
13877: dir: dir to create (including any subdirs under userfiles)
13878:
13879: =item *
13880:
13881: removeuserfile(): removes a file that exists in userfiles
13882:
13883: Args:
13884: docuname: username or courseid of destination for the file
13885: docudom: domain of user/course of destination for the file
13886: fname: filname to delete (including any subdirs under userfiles)
13887:
13888: =item *
13889:
13890: removeuploadedurl(): convience function for removeuserfile()
13891:
13892: Args:
13893: url: a full /uploaded/... url to delete
13894:
1.747 albertel 13895: =item *
13896:
13897: get_portfile_permissions():
13898: Args:
13899: domain: domain of user or course contain the portfolio files
13900: user: name of user or num of course contain the portfolio files
13901: Returns:
13902: hashref of a dump of the proper file_permissions.db
13903:
13904:
13905: =item *
13906:
13907: get_access_controls():
13908:
13909: Args:
13910: current_permissions: the hash ref returned from get_portfile_permissions()
13911: group: (optional) the group you want the files associated with
13912: file: (optional) the file you want access info on
13913:
13914: Returns:
1.749 raeburn 13915: a hash (keys are file names) of hashes containing
13916: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13917: values are XML containing access control settings (see below)
1.747 albertel 13918:
13919: Internal notes:
13920:
1.749 raeburn 13921: access controls are stored in file_permissions.db as key=value pairs.
13922: key -> path to file/file_name\0uniqueID:scope_end_start
13923: where scope -> public,guest,course,group,domains or users.
13924: end -> UNIX time for end of access (0 -> no end date)
13925: start -> UNIX time for start of access
13926:
13927: value -> XML description of access control
13928: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13929: <start></start>
13930: <end></end>
13931:
13932: <password></password> for scope type = guest
13933:
13934: <domain></domain> for scope type = course or group
13935: <number></number>
13936: <roles id="">
13937: <role></role>
13938: <access></access>
13939: <section></section>
13940: <group></group>
13941: </roles>
13942:
13943: <dom></dom> for scope type = domains
13944:
13945: <users> for scope type = users
13946: <user>
13947: <uname></uname>
13948: <udom></udom>
13949: </user>
13950: </users>
13951: </scope>
13952:
13953: Access data is also aggregated for each file in an additional key=value pair:
13954: key -> path to file/file_name\0accesscontrol
13955: value -> reference to hash
13956: hash contains key = value pairs
13957: where key = uniqueID:scope_end_start
13958: value = UNIX time record was last updated
13959:
13960: Used to improve speed of look-ups of access controls for each file.
13961:
13962: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13963:
1.1172.2.13 raeburn 13964: =item *
13965:
1.749 raeburn 13966: modify_access_controls():
13967:
13968: Modifies access controls for a portfolio file
13969: Args
13970: 1. file name
13971: 2. reference to hash of required changes,
13972: 3. domain
13973: 4. username
13974: where domain,username are the domain of the portfolio owner
13975: (either a user or a course)
13976:
13977: Returns:
13978: 1. result of additions or updates ('ok' or 'error', with error message).
13979: 2. result of deletions ('ok' or 'error', with error message).
13980: 3. reference to hash of any new or updated access controls.
13981: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13982: key = integer (inbound ID)
1.1172.2.13 raeburn 13983: value = uniqueID
13984:
13985: =item *
13986:
13987: get_timebased_id():
13988:
13989: Attempts to get a unique timestamp-based suffix for use with items added to a
13990: course via the Course Editor (e.g., folders, composite pages,
13991: group bulletin boards).
13992:
13993: Args: (first three required; six others optional)
13994:
13995: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13996: docssequence, or name of group
13997:
13998: 2. keyid (alphanumeric): name of temporary locking key in hash,
13999: e.g., num, boardids
14000:
14001: 3. namespace: name of gdbm file used to store suffixes already assigned;
14002: file will be named nohist_namespace.db
14003:
14004: 4. cdom: domain of course; default is current course domain from %env
14005:
14006: 5. cnum: course number; default is current course number from %env
14007:
14008: 6. idtype: set to concat if an additional digit is to be appended to the
14009: unix timestamp to form the suffix, if the plain timestamp is already
14010: in use. Default is to not do this, but simply increment the unix
14011: timestamp by 1 until a unique key is obtained.
14012:
14013: 7. who: holder of locking key; defaults to user:domain for user.
14014:
14015: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14016: retrying); default is 3.
14017:
14018: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14019:
14020: Returns:
14021:
14022: 1. suffix obtained (numeric)
14023:
14024: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14025:
14026: 3. error: contains (localized) error message if an error occurred.
14027:
1.747 albertel 14028:
1.608 albertel 14029: =back
14030:
1.243 albertel 14031: =head2 HTTP Helper Routines
14032:
14033: =over 4
14034:
1.191 harris41 14035: =item *
14036:
14037: escape() : unpack non-word characters into CGI-compatible hex codes
14038:
14039: =item *
14040:
14041: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14042:
1.243 albertel 14043: =back
14044:
14045: =head1 PRIVATE SUBROUTINES
14046:
14047: =head2 Underlying communication routines (Shouldn't call)
14048:
14049: =over 4
14050:
14051: =item *
14052:
14053: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14054:
14055: =item *
14056:
14057: reply() : uses subreply to send a message to remote machine, logs all failures
14058:
14059: =item *
14060:
14061: critical() : passes a critical message to another server; if cannot
14062: get through then place message in connection buffer directory and
14063: returns con_delayed, if incapable of saving message, returns
14064: con_failed
14065:
14066: =item *
14067:
14068: reconlonc() : tries to reconnect lonc client processes.
14069:
14070: =back
14071:
14072: =head2 Resource Access Logging
14073:
14074: =over 4
14075:
14076: =item *
14077:
14078: flushcourselogs() : flush (save) buffer logs and access logs
14079:
14080: =item *
14081:
14082: courselog($what) : save message for course in hash
14083:
14084: =item *
14085:
14086: courseacclog($what) : save message for course using &courselog(). Perform
14087: special processing for specific resource types (problems, exams, quizzes, etc).
14088:
1.191 harris41 14089: =item *
14090:
14091: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14092: as a PerlChildExitHandler
1.243 albertel 14093:
14094: =back
14095:
14096: =head2 Other
14097:
14098: =over 4
14099:
14100: =item *
14101:
14102: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14103:
14104: =back
14105:
14106: =cut
1.877 foxr 14107:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>