Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.60
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.60! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.59 2015/01/23 23:49:38 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'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
1.1172.2.41 raeburn 888: my ($try_server, $spare_server, $lowest_load, $required) = @_;
889:
890: if ($required) {
891: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
892: my $remoterev = &get_server_loncaparev(undef,$try_server);
893: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
894: if (($major eq '' && $minor eq '') ||
895: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
896: return ($spare_server,$lowest_load);
897: }
898: }
1.784 albertel 899:
900: my $loadans = &reply('load', $try_server);
901: my $userloadans = &reply('userload',$try_server);
902:
903: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 904: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 905: }
906:
907: my $load;
908: if ($loadans =~ /\d/) {
909: if ($userloadans =~ /\d/) {
910: #both are numbers, pick the bigger one
911: $load = ($loadans > $userloadans) ? $loadans
912: : $userloadans;
1.411 albertel 913: } else {
1.784 albertel 914: $load = $loadans;
1.411 albertel 915: }
1.784 albertel 916: } else {
917: $load = $userloadans;
918: }
919:
920: if (($load =~ /\d/) && ($load < $lowest_load)) {
921: $spare_server = $try_server;
922: $lowest_load = $load;
1.370 albertel 923: }
1.784 albertel 924: return ($spare_server,$lowest_load);
1.202 matthew 925: }
1.914 albertel 926:
927: # --------------------------- ask offload servers if user already has a session
928: sub find_existing_session {
929: my ($udom,$uname) = @_;
1.1123 raeburn 930: my $spareshash = &this_host_spares($udom);
931: if (ref($spareshash) eq 'HASH') {
932: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'primary'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
937: if (ref($spareshash->{'default'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'default'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
1.914 albertel 942: }
943: return;
944: }
945:
946: # -------------------------------- ask if server already has a session for user
947: sub has_user_session {
948: my ($lonid,$udom,$uname) = @_;
949: my $result = &reply(join(':','userhassession',
950: map {&escape($_)} ($udom,$uname)),$lonid);
951: return 1 if ($result eq 'ok');
952:
953: return 0;
954: }
955:
1.1076 raeburn 956: # --------- determine least loaded server in a user's domain which allows login
957:
958: sub choose_server {
1.1172.2.47 raeburn 959: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 960: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 961: my %servers = &get_servers($udom);
1.1076 raeburn 962: my $lowest_load = 30000;
1.1172.2.47 raeburn 963: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
964: if ($skiploadbal) {
965: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
966: unless (defined($cached)) {
967: my $cachetime = 60*60*24;
968: my %domconfig =
969: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
970: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
971: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
972: $cachetime);
973: }
974: }
975: }
1.1076 raeburn 976: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 977: my $loginvia;
1.1172.2.47 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: if ($checkloginvia) {
984: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 985: if ($loginvia) {
986: my ($server,$path) = split(/:/,$loginvia);
987: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 988: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 989: if ($login_host eq $server) {
990: $portal_path = $path;
1.1151 raeburn 991: $isredirect = 1;
1.1116 raeburn 992: }
993: } else {
994: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 995: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 996: if ($login_host eq $lonhost) {
997: $portal_path = '';
1.1151 raeburn 998: $isredirect = '';
1.1116 raeburn 999: }
1000: }
1001: } else {
1.1076 raeburn 1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1004: }
1005: }
1006: if ($login_host ne '') {
1.1116 raeburn 1007: $hostname = &hostname($login_host);
1.1076 raeburn 1008: }
1.1151 raeburn 1009: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1010: }
1011:
1.202 matthew 1012: # --------------------------------------------- Try to change a user's password
1013:
1014: sub changepass {
1.799 raeburn 1015: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1016: $currentpass = &escape($currentpass);
1017: $newpass = &escape($newpass);
1.1030 raeburn 1018: my $lonhost = $perlvar{'lonHostID'};
1019: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1020: $server);
1021: if (! $answer) {
1022: &logthis("No reply on password change request to $server ".
1023: "by $uname in domain $udom.");
1024: } elsif ($answer =~ "^ok") {
1025: &logthis("$uname in $udom successfully changed their password ".
1026: "on $server.");
1027: } elsif ($answer =~ "^pwchange_failure") {
1028: &logthis("$uname in $udom was unable to change their password ".
1029: "on $server. The action was blocked by either lcpasswd ".
1030: "or pwchange");
1031: } elsif ($answer =~ "^non_authorized") {
1032: &logthis("$uname in $udom did not get their password correct when ".
1033: "attempting to change it on $server.");
1034: } elsif ($answer =~ "^auth_mode_error") {
1035: &logthis("$uname in $udom attempted to change their password despite ".
1036: "not being locally or internally authenticated on $server.");
1037: } elsif ($answer =~ "^unknown_user") {
1038: &logthis("$uname in $udom attempted to change their password ".
1039: "on $server but were unable to because $server is not ".
1040: "their home server.");
1041: } elsif ($answer =~ "^refused") {
1042: &logthis("$server refused to change $uname in $udom password because ".
1043: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1044: } elsif ($answer =~ "invalid_client") {
1045: &logthis("$server refused to change $uname in $udom password because ".
1046: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1047: }
1048: return $answer;
1.1 albertel 1049: }
1050:
1.169 harris41 1051: # ----------------------- Try to determine user's current authentication scheme
1052:
1053: sub queryauthenticate {
1054: my ($uname,$udom)=@_;
1.456 albertel 1055: my $uhome=&homeserver($uname,$udom);
1056: if (!$uhome) {
1057: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1058: return 'no_host';
1059: }
1060: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1061: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1062: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1063: }
1.456 albertel 1064: return $answer;
1.169 harris41 1065: }
1066:
1.1 albertel 1067: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1068:
1.1 albertel 1069: sub authenticate {
1.1073 raeburn 1070: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1071: $upass=&escape($upass);
1072: $uname= &LONCAPA::clean_username($uname);
1.836 www 1073: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1074: my $newhome;
1.836 www 1075: if ((!$uhome) || ($uhome eq 'no_host')) {
1076: # Maybe the machine was offline and only re-appeared again recently?
1077: &reconlonc();
1078: # One more
1.952 raeburn 1079: $uhome=&homeserver($uname,$udom,1);
1080: if (($uhome eq 'no_host') && $checkdefauth) {
1081: if (defined(&domain($udom,'primary'))) {
1082: $newhome=&domain($udom,'primary');
1083: }
1084: if ($newhome ne '') {
1085: $uhome = $newhome;
1086: }
1087: }
1.836 www 1088: if ((!$uhome) || ($uhome eq 'no_host')) {
1089: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1090: return 'no_host';
1091: }
1.1 albertel 1092: }
1.1073 raeburn 1093: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1094: if ($answer eq 'authorized') {
1.952 raeburn 1095: if ($newhome) {
1096: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1097: return 'no_account_on_host';
1098: } else {
1099: &logthis("User $uname at $udom authorized by $uhome");
1100: return $uhome;
1101: }
1.471 albertel 1102: }
1103: if ($answer eq 'non_authorized') {
1104: &logthis("User $uname at $udom rejected by $uhome");
1105: return 'no_host';
1.9 www 1106: }
1.471 albertel 1107: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1108: return 'no_host';
1109: }
1110:
1.1073 raeburn 1111: sub can_host_session {
1.1074 raeburn 1112: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1113: my $canhost = 1;
1.1074 raeburn 1114: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1115: if (ref($remotesessions) eq 'HASH') {
1116: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1117: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1118: $canhost = 0;
1119: } else {
1120: $canhost = 1;
1121: }
1122: }
1123: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1124: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: if ($canhost) {
1131: if ($remotesessions->{'version'} ne '') {
1132: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1133: if ($reqmajor ne '' && $reqminor ne '') {
1134: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1135: my $major = $1;
1136: my $minor = $2;
1137: if (($major < $reqmajor ) ||
1138: (($major == $reqmajor) && ($minor < $reqminor))) {
1139: $canhost = 0;
1140: }
1141: } else {
1142: $canhost = 0;
1143: }
1144: }
1145: }
1146: }
1147: }
1148: if ($canhost) {
1149: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1150: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1151: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1152: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1153: if (($uint_dom ne '') &&
1154: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1155: $canhost = 0;
1156: } else {
1157: $canhost = 1;
1158: }
1159: }
1160: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1163: $canhost = 1;
1164: } else {
1165: $canhost = 0;
1166: }
1167: }
1168: }
1169: }
1170: return $canhost;
1171: }
1172:
1.1083 raeburn 1173: sub spare_can_host {
1174: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1175: my $canhost=1;
1176: my @intdoms;
1177: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1178: if (ref($internet_names) eq 'ARRAY') {
1179: @intdoms = @{$internet_names};
1180: }
1181: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1182: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1183: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1184: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1185: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1186: $canhost = &can_host_session($udom,$try_server,$remoterev,
1187: $remotesessions,
1188: $defdomdefaults{'hostedsessions'});
1189: }
1190: return $canhost;
1191: }
1192:
1.1123 raeburn 1193: sub this_host_spares {
1194: my ($dom) = @_;
1.1126 raeburn 1195: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1196: my @hosts = ¤t_machine_ids();
1197: foreach my $lonhost (@hosts) {
1198: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1199: $dom_in_use = $dom;
1200: $lonhost_in_use = $lonhost;
1.1123 raeburn 1201: last;
1202: }
1203: }
1.1126 raeburn 1204: if ($dom_in_use ne '') {
1205: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1206: }
1207: if (ref($result) ne 'HASH') {
1208: $lonhost_in_use = $perlvar{'lonHostID'};
1209: $dom_in_use = &host_domain($lonhost_in_use);
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: if (ref($result) ne 'HASH') {
1212: $result = \%spareid;
1213: }
1214: }
1215: return $result;
1216: }
1217:
1218: sub spares_for_offload {
1219: my ($dom_in_use,$lonhost_in_use) = @_;
1220: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1221: if (defined($cached)) {
1222: return $result;
1223: } else {
1.1126 raeburn 1224: my $cachetime = 60*60*24;
1225: my %domconfig =
1226: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1227: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1228: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1229: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1230: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1231: }
1232: }
1233: }
1234: }
1.1126 raeburn 1235: return;
1.1123 raeburn 1236: }
1237:
1.1129 raeburn 1238: sub get_lonbalancer_config {
1239: my ($servers) = @_;
1240: my ($currbalancer,$currtargets);
1241: if (ref($servers) eq 'HASH') {
1242: foreach my $server (keys(%{$servers})) {
1243: my %what = (
1244: spareid => 1,
1245: perlvar => 1,
1246: );
1247: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1248: if ($result eq 'ok') {
1249: if (ref($returnhash) eq 'HASH') {
1250: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1251: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1252: $currbalancer = $server;
1253: $currtargets = {};
1254: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1255: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1256: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1257: }
1258: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1259: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1260: }
1261: }
1262: last;
1263: }
1264: }
1265: }
1266: }
1267: }
1268: }
1269: return ($currbalancer,$currtargets);
1270: }
1271:
1272: sub check_loadbalancing {
1273: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1274: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1275: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1276: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1277: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1278: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1279: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1280: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1281: my $serverhomedom = &host_domain($lonhost);
1282:
1283: my $cachetime = 60*60*24;
1284:
1285: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1286: $dom_in_use = $udom;
1287: $homeintdom = 1;
1288: } else {
1289: $dom_in_use = $serverhomedom;
1290: }
1291: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1292: unless (defined($cached)) {
1293: my %domconfig =
1294: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1295: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1296: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1297: }
1298: }
1299: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1300: ($is_balancer,$currtargets,$currrules) =
1301: &check_balancer_result($result,@hosts);
1.1129 raeburn 1302: if ($is_balancer) {
1303: if (ref($currrules) eq 'HASH') {
1304: if ($homeintdom) {
1305: if ($uname ne '') {
1306: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1307: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1308: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1309: $rule_in_effect = $currrules->{'_LC_author'};
1310: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1311: $rule_in_effect = $currrules->{'_LC_adv'}
1312: }
1313: }
1314: if ($rule_in_effect eq '') {
1315: my %userenv = &userenvironment($udom,$uname,'inststatus');
1316: if ($userenv{'inststatus'} ne '') {
1317: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1318: my ($othertitle,$usertypes,$types) =
1319: &Apache::loncommon::sorted_inst_types($udom);
1320: if (ref($types) eq 'ARRAY') {
1321: foreach my $type (@{$types}) {
1322: if (grep(/^\Q$type\E$/,@statuses)) {
1323: if (exists($currrules->{$type})) {
1324: $rule_in_effect = $currrules->{$type};
1325: }
1326: }
1327: }
1328: }
1329: } else {
1330: if (exists($currrules->{'default'})) {
1331: $rule_in_effect = $currrules->{'default'};
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: } else {
1341: if ($currrules->{'_LC_external'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_external'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: }
1349: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1350: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1351: unless (defined($cached)) {
1352: my %domconfig =
1353: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1354: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1355: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1356: }
1357: }
1358: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1359: ($is_balancer,$currtargets,$currrules) =
1360: &check_balancer_result($result,@hosts);
1361: if ($is_balancer) {
1.1129 raeburn 1362: if (ref($currrules) eq 'HASH') {
1363: if ($currrules->{'_LC_internetdom'} ne '') {
1364: $rule_in_effect = $currrules->{'_LC_internetdom'};
1365: }
1366: }
1367: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1368: $uname,$udom);
1369: }
1370: } else {
1371: if ($perlvar{'lonBalancer'} eq 'yes') {
1372: $is_balancer = 1;
1373: $offloadto = &this_host_spares($dom_in_use);
1374: }
1375: }
1376: } else {
1377: if ($perlvar{'lonBalancer'} eq 'yes') {
1378: $is_balancer = 1;
1379: $offloadto = &this_host_spares($dom_in_use);
1380: }
1381: }
1.1172.2.5 raeburn 1382: if ($is_balancer) {
1383: my $lowest_load = 30000;
1384: if (ref($offloadto) eq 'HASH') {
1385: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1386: foreach my $try_server (@{$offloadto->{'primary'}}) {
1387: ($otherserver,$lowest_load) =
1388: &compare_server_load($try_server,$otherserver,$lowest_load);
1389: }
1.1129 raeburn 1390: }
1.1172.2.5 raeburn 1391: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1392:
1.1172.2.5 raeburn 1393: if (!$found_server) {
1394: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'default'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1399: }
1400: }
1401: } elsif (ref($offloadto) eq 'ARRAY') {
1402: if (@{$offloadto} == 1) {
1403: $otherserver = $offloadto->[0];
1404: } elsif (@{$offloadto} > 1) {
1405: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1406: ($otherserver,$lowest_load) =
1407: &compare_server_load($try_server,$otherserver,$lowest_load);
1408: }
1409: }
1410: }
1.1172.2.5 raeburn 1411: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1412: $is_balancer = 0;
1413: if ($uname ne '' && $udom ne '') {
1414: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1415:
1416: &appenv({'user.loadbalexempt' => $lonhost,
1417: 'user.loadbalcheck.time' => time});
1418: }
1.1129 raeburn 1419: }
1420: }
1421: }
1422: return ($is_balancer,$otherserver);
1423: }
1424:
1.1172.2.12 raeburn 1425: sub check_balancer_result {
1426: my ($result,@hosts) = @_;
1427: my ($is_balancer,$currtargets,$currrules);
1428: if (ref($result) eq 'HASH') {
1429: if ($result->{'lonhost'} ne '') {
1430: my $currbalancer = $result->{'lonhost'};
1431: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1432: $is_balancer = 1;
1433: $currtargets = $result->{'targets'};
1434: $currrules = $result->{'rules'};
1435: }
1436: } else {
1437: foreach my $key (keys(%{$result})) {
1438: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1439: (ref($result->{$key}) eq 'HASH')) {
1440: $is_balancer = 1;
1441: $currrules = $result->{$key}{'rules'};
1442: $currtargets = $result->{$key}{'targets'};
1443: last;
1444: }
1445: }
1446: }
1447: }
1448: return ($is_balancer,$currtargets,$currrules);
1449: }
1450:
1.1129 raeburn 1451: sub get_loadbalancer_targets {
1452: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1453: my $offloadto;
1.1172.2.4 raeburn 1454: if ($rule_in_effect eq 'none') {
1455: return [$perlvar{'lonHostID'}];
1456: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1457: $offloadto = $currtargets;
1458: } else {
1459: if ($rule_in_effect eq 'homeserver') {
1460: my $homeserver = &homeserver($uname,$udom);
1461: if ($homeserver ne 'no_host') {
1462: $offloadto = [$homeserver];
1463: }
1464: } elsif ($rule_in_effect eq 'externalbalancer') {
1465: my %domconfig =
1466: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1467: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1468: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1469: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1470: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1471: }
1472: }
1473: } else {
1.1172.2.7 raeburn 1474: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1475: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1476: if (&hostname($remotebalancer) ne '') {
1477: $offloadto = [$remotebalancer];
1478: }
1479: }
1480: } elsif (&hostname($rule_in_effect) ne '') {
1481: $offloadto = [$rule_in_effect];
1482: }
1483: }
1484: return $offloadto;
1485: }
1486:
1.1127 raeburn 1487: sub internet_dom_servers {
1488: my ($dom) = @_;
1489: my (%uniqservers,%servers);
1490: my $primaryserver = &hostname(&domain($dom,'primary'));
1491: my @machinedoms = &machine_domains($primaryserver);
1492: foreach my $mdom (@machinedoms) {
1493: my %currservers = %servers;
1494: my %server = &get_servers($mdom);
1495: %servers = (%currservers,%server);
1496: }
1497: my %by_hostname;
1498: foreach my $id (keys(%servers)) {
1499: push(@{$by_hostname{$servers{$id}}},$id);
1500: }
1501: foreach my $hostname (sort(keys(%by_hostname))) {
1502: if (@{$by_hostname{$hostname}} > 1) {
1503: my $match = 0;
1504: foreach my $id (@{$by_hostname{$hostname}}) {
1505: if (&host_domain($id) eq $dom) {
1506: $uniqservers{$id} = $hostname;
1507: $match = 1;
1508: }
1509: }
1510: unless ($match) {
1511: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1512: }
1513: } else {
1514: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1515: }
1516: }
1517: return %uniqservers;
1518: }
1519:
1.1 albertel 1520: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1521:
1.599 albertel 1522: my %homecache;
1.1 albertel 1523: sub homeserver {
1.230 stredwic 1524: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1525: my $index="$uname:$udom";
1.426 albertel 1526:
1.599 albertel 1527: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1528:
1529: my %servers = &get_servers($udom,'library');
1530: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1531: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1532: exists($badServerCache{$tryserver}));
1.841 albertel 1533:
1534: my $answer=reply("home:$udom:$uname",$tryserver);
1535: if ($answer eq 'found') {
1536: delete($badServerCache{$tryserver});
1537: return $homecache{$index}=$tryserver;
1538: } elsif ($answer eq 'no_host') {
1539: $badServerCache{$tryserver}=1;
1540: }
1.1 albertel 1541: }
1542: return 'no_host';
1.70 www 1543: }
1544:
1545: # ------------------------------------- Find the usernames behind a list of IDs
1546:
1547: sub idget {
1548: my ($udom,@ids)=@_;
1549: my %returnhash=();
1550:
1.841 albertel 1551: my %servers = &get_servers($udom,'library');
1552: foreach my $tryserver (keys(%servers)) {
1553: my $idlist=join('&',@ids);
1554: $idlist=~tr/A-Z/a-z/;
1555: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1556: my @answer=();
1557: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1558: @answer=split(/\&/,$reply);
1559: } ;
1560: my $i;
1561: for ($i=0;$i<=$#ids;$i++) {
1562: if ($answer[$i]) {
1563: $returnhash{$ids[$i]}=$answer[$i];
1564: }
1565: }
1566: }
1.70 www 1567: return %returnhash;
1568: }
1569:
1570: # ------------------------------------- Find the IDs behind a list of usernames
1571:
1572: sub idrget {
1573: my ($udom,@unames)=@_;
1574: my %returnhash=();
1.800 albertel 1575: foreach my $uname (@unames) {
1576: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1577: }
1.70 www 1578: return %returnhash;
1579: }
1580:
1581: # ------------------------------- Store away a list of names and associated IDs
1582:
1583: sub idput {
1584: my ($udom,%ids)=@_;
1585: my %servers=();
1.800 albertel 1586: foreach my $uname (keys(%ids)) {
1587: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1588: my $uhom=&homeserver($uname,$udom);
1.70 www 1589: if ($uhom ne 'no_host') {
1.800 albertel 1590: my $id=&escape($ids{$uname});
1.70 www 1591: $id=~tr/A-Z/a-z/;
1.800 albertel 1592: my $esc_unam=&escape($uname);
1.70 www 1593: if ($servers{$uhom}) {
1.800 albertel 1594: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1595: } else {
1.800 albertel 1596: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1597: }
1598: }
1.191 harris41 1599: }
1.800 albertel 1600: foreach my $server (keys(%servers)) {
1601: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1602: }
1.344 www 1603: }
1604:
1.1172.2.30 raeburn 1605: # ---------------------------------------- Delete unwanted IDs from ids.db file
1606:
1607: sub iddel {
1608: my ($udom,$idshashref,$uhome)=@_;
1609: my %result=();
1610: unless (ref($idshashref) eq 'HASH') {
1611: return %result;
1612: }
1613: my %servers=();
1614: while (my ($id,$uname) = each(%{$idshashref})) {
1615: my $uhom;
1616: if ($uhome) {
1617: $uhom = $uhome;
1618: } else {
1619: $uhom=&homeserver($uname,$udom);
1620: }
1621: if ($uhom ne 'no_host') {
1622: if ($servers{$uhom}) {
1623: $servers{$uhom}.='&'.&escape($id);
1624: } else {
1625: $servers{$uhom}=&escape($id);
1626: }
1627: }
1628: }
1629: foreach my $server (keys(%servers)) {
1630: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1631: }
1632: return %result;
1633: }
1634:
1.1023 raeburn 1635: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1636: sub dump_dom {
1.1165 droeschl 1637: my ($namespace, $udom, $regexp) = @_;
1638:
1639: $udom ||= $env{'user.domain'};
1640:
1641: return () unless $udom;
1642:
1643: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1644: }
1645:
1.1023 raeburn 1646: # ------------------------------------------ get items from domain db files
1.806 raeburn 1647:
1648: sub get_dom {
1.860 raeburn 1649: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1650: return if ($udom eq 'public');
1.806 raeburn 1651: my $items='';
1652: foreach my $item (@$storearr) {
1653: $items.=&escape($item).'&';
1654: }
1655: $items=~s/\&$//;
1.860 raeburn 1656: if (!$udom) {
1657: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1658: return if ($udom eq 'public');
1.860 raeburn 1659: if (defined(&domain($udom,'primary'))) {
1660: $uhome=&domain($udom,'primary');
1661: } else {
1.874 albertel 1662: undef($uhome);
1.860 raeburn 1663: }
1664: } else {
1665: if (!$uhome) {
1666: if (defined(&domain($udom,'primary'))) {
1667: $uhome=&domain($udom,'primary');
1668: }
1669: }
1670: }
1671: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1672: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1673: my %returnhash;
1.875 albertel 1674: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1675: return %returnhash;
1676: }
1.806 raeburn 1677: my @pairs=split(/\&/,$rep);
1678: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1679: return @pairs;
1680: }
1681: my $i=0;
1682: foreach my $item (@$storearr) {
1683: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1684: $i++;
1685: }
1686: return %returnhash;
1687: } else {
1.880 banghart 1688: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1689: }
1690: }
1691:
1692: # -------------------------------------------- put items in domain db files
1693:
1694: sub put_dom {
1.860 raeburn 1695: my ($namespace,$storehash,$udom,$uhome)=@_;
1696: if (!$udom) {
1697: $udom=$env{'user.domain'};
1698: if (defined(&domain($udom,'primary'))) {
1699: $uhome=&domain($udom,'primary');
1700: } else {
1.874 albertel 1701: undef($uhome);
1.860 raeburn 1702: }
1703: } else {
1704: if (!$uhome) {
1705: if (defined(&domain($udom,'primary'))) {
1706: $uhome=&domain($udom,'primary');
1707: }
1708: }
1709: }
1710: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1711: my $items='';
1712: foreach my $item (keys(%$storehash)) {
1713: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1714: }
1715: $items=~s/\&$//;
1716: return &reply("putdom:$udom:$namespace:$items",$uhome);
1717: } else {
1.860 raeburn 1718: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1719: }
1720: }
1721:
1.1023 raeburn 1722: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1723: sub newput_dom {
1.1023 raeburn 1724: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1725: my $result;
1726: if (!$udom) {
1727: $udom=$env{'user.domain'};
1728: }
1.1023 raeburn 1729: if ($udom) {
1730: my $uname = &get_domainconfiguser($udom);
1731: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1732: }
1733: return $result;
1734: }
1735:
1.1023 raeburn 1736: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1737: sub del_dom {
1.1023 raeburn 1738: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1739: if (ref($storearr) eq 'ARRAY') {
1740: if (!$udom) {
1741: $udom=$env{'user.domain'};
1742: }
1.1023 raeburn 1743: if ($udom) {
1744: my $uname = &get_domainconfiguser($udom);
1745: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1746: }
1747: }
1748: }
1749:
1.1023 raeburn 1750: # ----------------------------------construct domainconfig user for a domain
1751: sub get_domainconfiguser {
1752: my ($udom) = @_;
1753: return $udom.'-domainconfig';
1754: }
1755:
1.837 raeburn 1756: sub retrieve_inst_usertypes {
1757: my ($udom) = @_;
1758: my (%returnhash,@order);
1.989 raeburn 1759: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1760: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1761: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1762: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1763: } else {
1764: if (defined(&domain($udom,'primary'))) {
1765: my $uhome=&domain($udom,'primary');
1766: my $rep=&reply("inst_usertypes:$udom",$uhome);
1767: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1768: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1769: return (\%returnhash,\@order);
1770: }
1771: my ($hashitems,$orderitems) = split(/:/,$rep);
1772: my @pairs=split(/\&/,$hashitems);
1773: foreach my $item (@pairs) {
1774: my ($key,$value)=split(/=/,$item,2);
1775: $key = &unescape($key);
1776: next if ($key =~ /^error: 2 /);
1777: $returnhash{$key}=&thaw_unescape($value);
1778: }
1779: my @esc_order = split(/\&/,$orderitems);
1780: foreach my $item (@esc_order) {
1781: push(@order,&unescape($item));
1782: }
1783: } else {
1.1172.2.44 raeburn 1784: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1785: }
1.1172.2.44 raeburn 1786: return (\%returnhash,\@order);
1.837 raeburn 1787: }
1788: }
1789:
1.868 raeburn 1790: sub is_domainimage {
1791: my ($url) = @_;
1792: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1793: if (&domain($1) ne '') {
1794: return '1';
1795: }
1796: }
1797: return;
1798: }
1799:
1.899 raeburn 1800: sub inst_directory_query {
1801: my ($srch) = @_;
1802: my $udom = $srch->{'srchdomain'};
1803: my %results;
1804: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1805: my $outcome;
1.899 raeburn 1806: if ($homeserver ne '') {
1.904 albertel 1807: my $queryid=&reply("querysend:instdirsearch:".
1808: &escape($srch->{'srchby'}).':'.
1809: &escape($srch->{'srchterm'}).':'.
1810: &escape($srch->{'srchtype'}),$homeserver);
1811: my $host=&hostname($homeserver);
1812: if ($queryid !~/^\Q$host\E\_/) {
1813: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1814: return;
1815: }
1816: my $response = &get_query_reply($queryid);
1817: my $maxtries = 5;
1818: my $tries = 1;
1819: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1820: $response = &get_query_reply($queryid);
1821: $tries ++;
1822: }
1823:
1824: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1825: if ($response eq 'unavailable') {
1826: $outcome = $response;
1827: } else {
1828: $outcome = 'ok';
1829: my @matches = split(/\n/,$response);
1830: foreach my $match (@matches) {
1831: my ($key,$value) = split(/=/,$match);
1832: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1833: }
1.899 raeburn 1834: }
1835: }
1836: }
1.909 raeburn 1837: return ($outcome,%results);
1.899 raeburn 1838: }
1839:
1840: sub usersearch {
1841: my ($srch) = @_;
1842: my $dom = $srch->{'srchdomain'};
1843: my %results;
1844: my %libserv = &all_library();
1845: my $query = 'usersearch';
1846: foreach my $tryserver (keys(%libserv)) {
1847: if (&host_domain($tryserver) eq $dom) {
1848: my $host=&hostname($tryserver);
1849: my $queryid=
1.911 raeburn 1850: &reply("querysend:".&escape($query).':'.
1851: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1852: &escape($srch->{'srchtype'}).':'.
1853: &escape($srch->{'srchterm'}),$tryserver);
1854: if ($queryid !~/^\Q$host\E\_/) {
1855: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1856: next;
1.899 raeburn 1857: }
1858: my $reply = &get_query_reply($queryid);
1859: my $maxtries = 1;
1860: my $tries = 1;
1861: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1862: $reply = &get_query_reply($queryid);
1863: $tries ++;
1864: }
1865: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1866: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1867: } else {
1.911 raeburn 1868: my @matches;
1869: if ($reply =~ /\n/) {
1870: @matches = split(/\n/,$reply);
1871: } else {
1872: @matches = split(/\&/,$reply);
1873: }
1.899 raeburn 1874: foreach my $match (@matches) {
1875: my ($uname,$udom,%userhash);
1.911 raeburn 1876: foreach my $entry (split(/:/,$match)) {
1877: my ($key,$value) =
1878: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1879: $userhash{$key} = $value;
1880: if ($key eq 'username') {
1881: $uname = $value;
1882: } elsif ($key eq 'domain') {
1883: $udom = $value;
1.911 raeburn 1884: }
1.899 raeburn 1885: }
1886: $results{$uname.':'.$udom} = \%userhash;
1887: }
1888: }
1889: }
1890: }
1891: return %results;
1892: }
1893:
1.912 raeburn 1894: sub get_instuser {
1895: my ($udom,$uname,$id) = @_;
1896: my $homeserver = &domain($udom,'primary');
1897: my ($outcome,%results);
1898: if ($homeserver ne '') {
1899: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1900: &escape($id).':'.&escape($udom),$homeserver);
1901: my $host=&hostname($homeserver);
1902: if ($queryid !~/^\Q$host\E\_/) {
1903: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1904: return;
1905: }
1906: my $response = &get_query_reply($queryid);
1907: my $maxtries = 5;
1908: my $tries = 1;
1909: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1910: $response = &get_query_reply($queryid);
1911: $tries ++;
1912: }
1913: if (!&error($response) && $response ne 'refused') {
1914: if ($response eq 'unavailable') {
1915: $outcome = $response;
1916: } else {
1917: $outcome = 'ok';
1918: my @matches = split(/\n/,$response);
1919: foreach my $match (@matches) {
1920: my ($key,$value) = split(/=/,$match);
1921: $results{&unescape($key)} = &thaw_unescape($value);
1922: }
1923: }
1924: }
1925: }
1926: my %userinfo;
1927: if (ref($results{$uname}) eq 'HASH') {
1928: %userinfo = %{$results{$uname}};
1929: }
1930: return ($outcome,%userinfo);
1931: }
1932:
1933: sub inst_rulecheck {
1.923 raeburn 1934: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1935: my %returnhash;
1936: if ($udom ne '') {
1937: if (ref($rules) eq 'ARRAY') {
1938: @{$rules} = map {&escape($_);} (@{$rules});
1939: my $rulestr = join(':',@{$rules});
1940: my $homeserver=&domain($udom,'primary');
1941: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1942: my $response;
1943: if ($item eq 'username') {
1944: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1945: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1946: $homeserver));
1.923 raeburn 1947: } elsif ($item eq 'id') {
1948: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1949: ':'.&escape($id).':'.$rulestr,
1950: $homeserver));
1.945 raeburn 1951: } elsif ($item eq 'selfcreate') {
1952: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1953: &escape($udom).':'.&escape($uname).
1954: ':'.$rulestr,$homeserver));
1.923 raeburn 1955: }
1.912 raeburn 1956: if ($response ne 'refused') {
1957: my @pairs=split(/\&/,$response);
1958: foreach my $item (@pairs) {
1959: my ($key,$value)=split(/=/,$item,2);
1960: $key = &unescape($key);
1961: next if ($key =~ /^error: 2 /);
1962: $returnhash{$key}=&thaw_unescape($value);
1963: }
1964: }
1965: }
1966: }
1967: }
1968: return %returnhash;
1969: }
1970:
1971: sub inst_userrules {
1.923 raeburn 1972: my ($udom,$check) = @_;
1.912 raeburn 1973: my (%ruleshash,@ruleorder);
1974: if ($udom ne '') {
1975: my $homeserver=&domain($udom,'primary');
1976: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1977: my $response;
1978: if ($check eq 'id') {
1979: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1980: $homeserver);
1.943 raeburn 1981: } elsif ($check eq 'email') {
1982: $response=&reply('instemailrules:'.&escape($udom),
1983: $homeserver);
1.923 raeburn 1984: } else {
1985: $response=&reply('instuserrules:'.&escape($udom),
1986: $homeserver);
1987: }
1.912 raeburn 1988: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1989: ($response ne 'unknown_cmd') &&
1.912 raeburn 1990: ($response ne 'no_such_host')) {
1991: my ($hashitems,$orderitems) = split(/:/,$response);
1992: my @pairs=split(/\&/,$hashitems);
1993: foreach my $item (@pairs) {
1994: my ($key,$value)=split(/=/,$item,2);
1995: $key = &unescape($key);
1996: next if ($key =~ /^error: 2 /);
1997: $ruleshash{$key}=&thaw_unescape($value);
1998: }
1999: my @esc_order = split(/\&/,$orderitems);
2000: foreach my $item (@esc_order) {
2001: push(@ruleorder,&unescape($item));
2002: }
2003: }
2004: }
2005: }
2006: return (\%ruleshash,\@ruleorder);
2007: }
2008:
1.976 raeburn 2009: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2010:
2011: sub get_domain_defaults {
1.1172.2.35 raeburn 2012: my ($domain,$ignore_cache) = @_;
2013: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2014: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2015: unless ($ignore_cache) {
2016: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2017: if (defined($cached)) {
2018: if (ref($result) eq 'HASH') {
2019: return %{$result};
2020: }
1.943 raeburn 2021: }
2022: }
2023: my %domdefaults;
2024: my %domconfig =
1.989 raeburn 2025: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2026: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2027: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2028: 'requestauthor','selfenrollment',
2029: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2030: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2031: if (ref($domconfig{'defaults'}) eq 'HASH') {
2032: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2033: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2034: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2035: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2036: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2037: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2038: } else {
2039: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2040: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2041: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2042: }
1.976 raeburn 2043: if (ref($domconfig{'quotas'}) eq 'HASH') {
2044: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2045: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2046: } else {
2047: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2048: }
1.1172.2.6 raeburn 2049: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2050: foreach my $item (@usertools) {
2051: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2052: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2053: }
2054: }
1.1172.2.29 raeburn 2055: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2056: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2057: }
1.976 raeburn 2058: }
1.985 raeburn 2059: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2060: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2061: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2062: }
2063: }
1.1172.2.9 raeburn 2064: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2065: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2066: }
1.989 raeburn 2067: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2068: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2069: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2070: }
2071: }
1.1047 raeburn 2072: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60! raeburn 2073: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
! 2074: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
! 2075: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
! 2076: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
! 2077: }
1.1172.2.41 raeburn 2078: foreach my $type (@coursetypes) {
2079: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2080: unless ($type eq 'community') {
2081: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2082: }
2083: }
2084: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2085: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2086: }
1.1172.2.60! raeburn 2087: if ($domdefaults{'postsubmit'} eq 'on') {
! 2088: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
! 2089: $domdefaults{$type.'postsubtimeout'} =
! 2090: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
! 2091: }
! 2092: }
1.1172.2.30 raeburn 2093: }
1.1047 raeburn 2094: }
1.1073 raeburn 2095: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2096: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2097: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2098: }
2099: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2100: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2101: }
2102: }
1.1172.2.41 raeburn 2103: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2104: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2105: my @settings = ('types','registered','enroll_dates','access_dates','section',
2106: 'approval','limit');
2107: foreach my $type (@coursetypes) {
2108: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2109: my @mgrdc = ();
2110: foreach my $item (@settings) {
2111: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2112: push(@mgrdc,$item);
2113: }
2114: }
2115: if (@mgrdc) {
2116: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2117: }
2118: }
2119: }
2120: }
2121: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2122: foreach my $type (@coursetypes) {
2123: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2124: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2125: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2126: }
2127: }
2128: }
2129: }
2130: }
1.1172.2.46 raeburn 2131: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2132: $domdefaults{'catauth'} = 'std';
2133: $domdefaults{'catunauth'} = 'std';
2134: if ($domconfig{'coursecategories'}{'auth'}) {
2135: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2136: }
2137: if ($domconfig{'coursecategories'}{'unauth'}) {
2138: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2139: }
2140: }
1.1172.2.23 raeburn 2141: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2142: return %domdefaults;
2143: }
2144:
1.344 www 2145: # --------------------------------------------------- Assign a key to a student
2146:
2147: sub assign_access_key {
1.364 www 2148: #
2149: # a valid key looks like uname:udom#comments
2150: # comments are being appended
2151: #
1.498 www 2152: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2153: $kdom=
1.620 albertel 2154: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2155: $knum=
1.620 albertel 2156: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2157: $cdom=
1.620 albertel 2158: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2159: $cnum=
1.620 albertel 2160: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2161: $udom=$env{'user.name'} unless (defined($udom));
2162: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2163: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2164: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2165: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2166: # assigned to this person
2167: # - this should not happen,
1.345 www 2168: # unless something went wrong
2169: # the first time around
2170: # ready to assign
1.364 www 2171: $logentry=$1.'; '.$logentry;
1.496 www 2172: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2173: $kdom,$knum) eq 'ok') {
1.345 www 2174: # key now belongs to user
1.346 www 2175: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2176: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2177: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2178: return 'ok';
2179: } else {
2180: return
2181: 'error: Count not permanently assign key, will need to be re-entered later.';
2182: }
2183: } else {
2184: return 'error: Could not assign key, try again later.';
2185: }
1.364 www 2186: } elsif (!$existing{$ckey}) {
1.345 www 2187: # the key does not exist
2188: return 'error: The key does not exist';
2189: } else {
2190: # the key is somebody else's
2191: return 'error: The key is already in use';
2192: }
1.344 www 2193: }
2194:
1.364 www 2195: # ------------------------------------------ put an additional comment on a key
2196:
2197: sub comment_access_key {
2198: #
2199: # a valid key looks like uname:udom#comments
2200: # comments are being appended
2201: #
2202: my ($ckey,$cdom,$cnum,$logentry)=@_;
2203: $cdom=
1.620 albertel 2204: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2205: $cnum=
1.620 albertel 2206: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2207: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2208: if ($existing{$ckey}) {
2209: $existing{$ckey}.='; '.$logentry;
2210: # ready to assign
1.367 www 2211: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2212: $cdom,$cnum) eq 'ok') {
2213: return 'ok';
2214: } else {
2215: return 'error: Count not store comment.';
2216: }
2217: } else {
2218: # the key does not exist
2219: return 'error: The key does not exist';
2220: }
2221: }
2222:
1.344 www 2223: # ------------------------------------------------------ Generate a set of keys
2224:
2225: sub generate_access_keys {
1.364 www 2226: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2227: $cdom=
1.620 albertel 2228: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2229: $cnum=
1.620 albertel 2230: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2231: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2232: unless (($cdom) && ($cnum)) { return 0; }
2233: if ($number>10000) { return 0; }
2234: sleep(2); # make sure don't get same seed twice
2235: srand(time()^($$+($$<<15))); # from "Programming Perl"
2236: my $total=0;
2237: for (my $i=1;$i<=$number;$i++) {
2238: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2239: sprintf("%lx",int(100000*rand)).'-'.
2240: sprintf("%lx",int(100000*rand));
2241: $newkey=~s/1/g/g; # folks mix up 1 and l
2242: $newkey=~s/0/h/g; # and also 0 and O
2243: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2244: if ($existing{$newkey}) {
2245: $i--;
2246: } else {
1.364 www 2247: if (&put('accesskeys',
2248: { $newkey => '# generated '.localtime().
1.620 albertel 2249: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2250: '; '.$logentry },
2251: $cdom,$cnum) eq 'ok') {
1.344 www 2252: $total++;
2253: }
2254: }
2255: }
1.620 albertel 2256: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2257: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2258: return $total;
2259: }
2260:
2261: # ------------------------------------------------------- Validate an accesskey
2262:
2263: sub validate_access_key {
2264: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2265: $cdom=
1.620 albertel 2266: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2267: $cnum=
1.620 albertel 2268: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2269: $udom=$env{'user.domain'} unless (defined($udom));
2270: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2271: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2272: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2273: }
2274:
2275: # ------------------------------------- Find the section of student in a course
1.652 albertel 2276: sub devalidate_getsection_cache {
2277: my ($udom,$unam,$courseid)=@_;
2278: my $hashid="$udom:$unam:$courseid";
2279: &devalidate_cache_new('getsection',$hashid);
2280: }
1.298 matthew 2281:
1.815 albertel 2282: sub courseid_to_courseurl {
2283: my ($courseid) = @_;
2284: #already url style courseid
2285: return $courseid if ($courseid =~ m{^/});
2286:
2287: if (exists($env{'course.'.$courseid.'.num'})) {
2288: my $cnum = $env{'course.'.$courseid.'.num'};
2289: my $cdom = $env{'course.'.$courseid.'.domain'};
2290: return "/$cdom/$cnum";
2291: }
2292:
2293: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2294: if (exists($courseinfo{'num'})) {
2295: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2296: }
2297:
2298: return undef;
2299: }
2300:
1.298 matthew 2301: sub getsection {
2302: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2303: my $cachetime=1800;
1.551 albertel 2304:
2305: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2306: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2307: if (defined($cached)) { return $result; }
2308:
1.298 matthew 2309: my %Pending;
2310: my %Expired;
2311: #
2312: # Each role can either have not started yet (pending), be active,
2313: # or have expired.
2314: #
2315: # If there is an active role, we are done.
2316: #
2317: # If there is more than one role which has not started yet,
2318: # choose the one which will start sooner
2319: # If there is one role which has not started yet, return it.
2320: #
2321: # If there is more than one expired role, choose the one which ended last.
2322: # If there is a role which has expired, return it.
2323: #
1.815 albertel 2324: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2325: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2326: foreach my $key (keys(%roleshash)) {
1.479 albertel 2327: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2328: my $section=$1;
2329: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2330: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2331: my $now=time;
1.548 albertel 2332: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2333: $Expired{$end}=$section;
2334: next;
2335: }
1.548 albertel 2336: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2337: $Pending{$start}=$section;
2338: next;
2339: }
1.599 albertel 2340: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2341: }
2342: #
2343: # Presumedly there will be few matching roles from the above
2344: # loop and the sorting time will be negligible.
2345: if (scalar(keys(%Pending))) {
2346: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2347: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2348: }
2349: if (scalar(keys(%Expired))) {
2350: my @sorted = sort {$a <=> $b} keys(%Expired);
2351: my $time = pop(@sorted);
1.599 albertel 2352: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2353: }
1.599 albertel 2354: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2355: }
1.70 www 2356:
1.599 albertel 2357: sub save_cache {
2358: &purge_remembered();
1.722 albertel 2359: #&Apache::loncommon::validate_page();
1.620 albertel 2360: undef(%env);
1.780 albertel 2361: undef($env_loaded);
1.599 albertel 2362: }
1.452 albertel 2363:
1.599 albertel 2364: my $to_remember=-1;
2365: my %remembered;
2366: my %accessed;
2367: my $kicks=0;
2368: my $hits=0;
1.849 albertel 2369: sub make_key {
2370: my ($name,$id) = @_;
1.872 albertel 2371: if (length($id) > 65
2372: && length(&escape($id)) > 200) {
2373: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2374: }
1.849 albertel 2375: return &escape($name.':'.$id);
2376: }
2377:
1.599 albertel 2378: sub devalidate_cache_new {
2379: my ($name,$id,$debug) = @_;
2380: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2381: $id=&make_key($name,$id);
1.599 albertel 2382: $memcache->delete($id);
2383: delete($remembered{$id});
2384: delete($accessed{$id});
2385: }
2386:
2387: sub is_cached_new {
2388: my ($name,$id,$debug) = @_;
1.849 albertel 2389: $id=&make_key($name,$id);
1.599 albertel 2390: if (exists($remembered{$id})) {
1.1133 foxr 2391: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2392: $accessed{$id}=[&gettimeofday()];
2393: $hits++;
2394: return ($remembered{$id},1);
2395: }
2396: my $value = $memcache->get($id);
2397: if (!(defined($value))) {
2398: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2399: return (undef,undef);
1.416 albertel 2400: }
1.599 albertel 2401: if ($value eq '__undef__') {
2402: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2403: $value=undef;
2404: }
2405: &make_room($id,$value,$debug);
2406: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2407: return ($value,1);
2408: }
2409:
2410: sub do_cache_new {
2411: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2412: $id=&make_key($name,$id);
1.599 albertel 2413: my $setvalue=$value;
2414: if (!defined($setvalue)) {
2415: $setvalue='__undef__';
2416: }
1.623 albertel 2417: if (!defined($time) ) {
2418: $time=600;
2419: }
1.599 albertel 2420: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2421: my $result = $memcache->set($id,$setvalue,$time);
2422: if (! $result) {
1.872 albertel 2423: &logthis("caching of id -> $id failed");
1.910 albertel 2424: $memcache->disconnect_all();
1.872 albertel 2425: }
1.600 albertel 2426: # need to make a copy of $value
1.919 albertel 2427: &make_room($id,$value,$debug);
1.599 albertel 2428: return $value;
2429: }
2430:
2431: sub make_room {
2432: my ($id,$value,$debug)=@_;
1.919 albertel 2433:
2434: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2435: : $value;
1.599 albertel 2436: if ($to_remember<0) { return; }
2437: $accessed{$id}=[&gettimeofday()];
2438: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2439: my $to_kick;
2440: my $max_time=0;
2441: foreach my $other (keys(%accessed)) {
2442: if (&tv_interval($accessed{$other}) > $max_time) {
2443: $to_kick=$other;
2444: $max_time=&tv_interval($accessed{$other});
2445: }
2446: }
2447: delete($remembered{$to_kick});
2448: delete($accessed{$to_kick});
2449: $kicks++;
2450: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2451: return;
2452: }
2453:
1.599 albertel 2454: sub purge_remembered {
1.604 albertel 2455: #&logthis("Tossing ".scalar(keys(%remembered)));
2456: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2457: undef(%remembered);
2458: undef(%accessed);
1.428 albertel 2459: }
1.70 www 2460: # ------------------------------------- Read an entry from a user's environment
2461:
2462: sub userenvironment {
2463: my ($udom,$unam,@what)=@_;
1.976 raeburn 2464: my $items;
2465: foreach my $item (@what) {
2466: $items.=&escape($item).'&';
2467: }
2468: $items=~s/\&$//;
1.70 www 2469: my %returnhash=();
1.1009 raeburn 2470: my $uhome = &homeserver($unam,$udom);
2471: unless ($uhome eq 'no_host') {
2472: my @answer=split(/\&/,
2473: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2474: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2475: return %returnhash;
2476: }
1.1009 raeburn 2477: my $i;
2478: for ($i=0;$i<=$#what;$i++) {
2479: $returnhash{$what[$i]}=&unescape($answer[$i]);
2480: }
1.70 www 2481: }
2482: return %returnhash;
1.1 albertel 2483: }
2484:
1.617 albertel 2485: # ---------------------------------------------------------- Get a studentphoto
2486: sub studentphoto {
2487: my ($udom,$unam,$ext) = @_;
2488: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2489: if (defined($env{'request.course.id'})) {
1.708 raeburn 2490: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2491: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2492: return(&retrievestudentphoto($udom,$unam,$ext));
2493: } else {
2494: my ($result,$perm_reqd)=
1.707 albertel 2495: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2496: if ($result eq 'ok') {
2497: if (!($perm_reqd eq 'yes')) {
2498: return(&retrievestudentphoto($udom,$unam,$ext));
2499: }
2500: }
2501: }
2502: }
2503: } else {
2504: my ($result,$perm_reqd) =
1.707 albertel 2505: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2506: if ($result eq 'ok') {
2507: if (!($perm_reqd eq 'yes')) {
2508: return(&retrievestudentphoto($udom,$unam,$ext));
2509: }
2510: }
2511: }
2512: return '/adm/lonKaputt/lonlogo_broken.gif';
2513: }
2514:
2515: sub retrievestudentphoto {
2516: my ($udom,$unam,$ext,$type) = @_;
2517: my $home=&Apache::lonnet::homeserver($unam,$udom);
2518: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2519: if ($ret eq 'ok') {
2520: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2521: if ($type eq 'thumbnail') {
2522: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2523: }
2524: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2525: return $tokenurl;
2526: } else {
2527: if ($type eq 'thumbnail') {
2528: return '/adm/lonKaputt/genericstudent_tn.gif';
2529: } else {
2530: return '/adm/lonKaputt/lonlogo_broken.gif';
2531: }
1.617 albertel 2532: }
2533: }
2534:
1.263 www 2535: # -------------------------------------------------------------------- New chat
2536:
2537: sub chatsend {
1.724 raeburn 2538: my ($newentry,$anon,$group)=@_;
1.620 albertel 2539: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2540: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2541: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2542: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2543: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2544: &escape($newentry)).':'.$group,$chome);
1.292 www 2545: }
2546:
2547: # ------------------------------------------ Find current version of a resource
2548:
2549: sub getversion {
2550: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2551: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2552: return ¤tversion(&filelocation('',$fname));
2553: }
2554:
2555: sub currentversion {
2556: my $fname=shift;
2557: my $author=$fname;
2558: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2559: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2560: my $home=&homeserver($uname,$udom);
1.292 www 2561: if ($home eq 'no_host') {
2562: return -1;
2563: }
1.1112 www 2564: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2565: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2566: return -1;
2567: }
1.1112 www 2568: return $answer;
1.263 www 2569: }
2570:
1.1111 www 2571: #
2572: # Return special version number of resource if set by override, empty otherwise
2573: #
2574: sub usedversion {
2575: my $fname=shift;
2576: unless ($fname) { $fname=$env{'request.uri'}; }
2577: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2578: if ($urlversion) { return $urlversion; }
2579: return '';
2580: }
2581:
1.1 albertel 2582: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2583:
1.1 albertel 2584: sub subscribe {
2585: my $fname=shift;
1.761 raeburn 2586: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2587: $fname=~s/[\n\r]//g;
1.1 albertel 2588: my $author=$fname;
2589: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2590: my ($udom,$uname)=split(/\//,$author);
2591: my $home=homeserver($uname,$udom);
1.335 albertel 2592: if ($home eq 'no_host') {
2593: return 'not_found';
1.1 albertel 2594: }
2595: my $answer=reply("sub:$fname",$home);
1.64 www 2596: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2597: $answer.=' by '.$home;
2598: }
1.1 albertel 2599: return $answer;
2600: }
2601:
1.8 www 2602: # -------------------------------------------------------------- Replicate file
2603:
2604: sub repcopy {
2605: my $filename=shift;
1.23 www 2606: $filename=~s/\/+/\//g;
1.1142 raeburn 2607: my $londocroot = $perlvar{'lonDocRoot'};
2608: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2609: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2610: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2611: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2612: return &repcopy_userfile($filename);
2613: }
1.532 albertel 2614: $filename=~s/[\n\r]//g;
1.8 www 2615: my $transname="$filename.in.transfer";
1.828 www 2616: # FIXME: this should flock
1.607 raeburn 2617: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2618: my $remoteurl=subscribe($filename);
1.64 www 2619: if ($remoteurl =~ /^con_lost by/) {
2620: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2621: return 'unavailable';
1.8 www 2622: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2623: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2624: return 'not_found';
1.64 www 2625: } elsif ($remoteurl =~ /^rejected by/) {
2626: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2627: return 'forbidden';
1.20 www 2628: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2629: return 'ok';
1.8 www 2630: } else {
1.290 www 2631: my $author=$filename;
2632: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2633: my ($udom,$uname)=split(/\//,$author);
2634: my $home=homeserver($uname,$udom);
2635: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2636: my @parts=split(/\//,$filename);
2637: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2638: if ($path ne "$londocroot/res") {
1.8 www 2639: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2640: return 'bad_request';
1.8 www 2641: }
2642: my $count;
2643: for ($count=5;$count<$#parts;$count++) {
2644: $path.="/$parts[$count]";
2645: if ((-e $path)!=1) {
2646: mkdir($path,0777);
2647: }
2648: }
2649: my $ua=new LWP::UserAgent;
2650: my $request=new HTTP::Request('GET',"$remoteurl");
2651: my $response=$ua->request($request,$transname);
2652: if ($response->is_error()) {
2653: unlink($transname);
2654: my $message=$response->status_line;
1.672 albertel 2655: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2656: ." LWP get: $message: $filename</font>");
1.607 raeburn 2657: return 'unavailable';
1.8 www 2658: } else {
1.16 www 2659: if ($remoteurl!~/\.meta$/) {
2660: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2661: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2662: if ($mresponse->is_error()) {
2663: unlink($filename.'.meta');
2664: &logthis(
1.672 albertel 2665: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2666: }
2667: }
1.8 www 2668: rename($transname,$filename);
1.607 raeburn 2669: return 'ok';
1.8 www 2670: }
1.290 www 2671: }
1.8 www 2672: }
1.330 www 2673: }
2674:
2675: # ------------------------------------------------ Get server side include body
2676: sub ssi_body {
1.381 albertel 2677: my ($filelink,%form)=@_;
1.606 matthew 2678: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2679: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2680: }
1.953 www 2681: my $output='';
2682: my $response;
1.980 raeburn 2683: if ($filelink=~/^https?\:/) {
1.954 raeburn 2684: ($output,$response)=&externalssi($filelink);
1.953 www 2685: } else {
1.1004 droeschl 2686: $filelink .= $filelink=~/\?/ ? '&' : '?';
2687: $filelink .= 'inhibitmenu=yes';
1.953 www 2688: ($output,$response)=&ssi($filelink,%form);
2689: }
1.778 albertel 2690: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2691: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2692: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2693: if (wantarray) {
2694: return ($output, $response);
2695: } else {
2696: return $output;
2697: }
1.8 www 2698: }
2699:
1.15 www 2700: # --------------------------------------------------------- Server Side Include
2701:
1.782 albertel 2702: sub absolute_url {
2703: my ($host_name) = @_;
2704: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2705: if ($host_name eq '') {
2706: $host_name = $ENV{'SERVER_NAME'};
2707: }
2708: return $protocol.$host_name;
2709: }
2710:
1.942 foxr 2711: #
2712: # Server side include.
2713: # Parameters:
2714: # fn Possibly encrypted resource name/id.
2715: # form Hash that describes how the rendering should be done
2716: # and other things.
1.944 foxr 2717: # Returns:
1.950 raeburn 2718: # Scalar context: The content of the response.
2719: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2720: #
1.15 www 2721: sub ssi {
2722:
1.944 foxr 2723: my ($fn,%form)=@_;
1.15 www 2724: my $ua=new LWP::UserAgent;
1.23 www 2725: my $request;
1.711 albertel 2726:
2727: $form{'no_update_last_known'}=1;
1.895 albertel 2728: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2729: if (%form) {
1.782 albertel 2730: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2731: $request->content(join('&',map {
2732: my $name = escape($_);
2733: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2734: ? join("&$name=", map {escape($_) } @{$form{$_}})
2735: : &escape($form{$_}) );
2736: } keys(%form)));
1.23 www 2737: } else {
1.782 albertel 2738: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2739: }
2740:
1.15 www 2741: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2742: my $response= $ua->request($request);
1.944 foxr 2743: if (wantarray) {
1.1172.2.3 raeburn 2744: return ($response->content, $response);
1.944 foxr 2745: } else {
1.1172.2.3 raeburn 2746: return $response->content;
1.942 foxr 2747: }
1.324 www 2748: }
2749:
2750: sub externalssi {
2751: my ($url)=@_;
2752: my $ua=new LWP::UserAgent;
2753: my $request=new HTTP::Request('GET',$url);
2754: my $response=$ua->request($request);
1.954 raeburn 2755: if (wantarray) {
2756: return ($response->content, $response);
2757: } else {
2758: return $response->content;
2759: }
1.15 www 2760: }
1.254 www 2761:
1.492 albertel 2762: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2763:
2764: sub allowuploaded {
2765: my ($srcurl,$url)=@_;
2766: $url=&clutter(&declutter($url));
2767: my $dir=$url;
2768: $dir=~s/\/[^\/]+$//;
2769: my %httpref=();
2770: my $httpurl=&hreflocation('',$url);
2771: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2772: &Apache::lonnet::appenv(\%httpref);
1.254 www 2773: }
1.477 raeburn 2774:
1.1172.2.13 raeburn 2775: #
2776: # Determine if the current user should be able to edit a particular resource,
2777: # when viewing in course context.
2778: # (a) When viewing resource used to determine if "Edit" item is included in
2779: # Functions.
2780: # (b) When displaying folder contents in course editor, used to determine if
2781: # "Edit" link will be displayed alongside resource.
2782: #
2783: # input: six args -- filename (decluttered), course number, course domain,
2784: # url, symb (if registered) and group (if this is a group
2785: # item -- e.g., bulletin board, group page etc.).
2786: # output: array of five scalars --
2787: # $cfile -- url for file editing if editable on current server
2788: # $home -- homeserver of resource (i.e., for author if published,
2789: # or course if uploaded.).
2790: # $switchserver -- 1 if server switch will be needed.
2791: # $forceedit -- 1 if icon/link should be to go to edit mode
2792: # $forceview -- 1 if icon/link should be to go to view mode
2793: #
2794:
2795: sub can_edit_resource {
2796: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2797: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2798: #
2799: # For aboutme pages user can only edit his/her own.
2800: #
2801: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2802: my ($sdom,$sname) = ($1,$2);
2803: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2804: $home = $env{'user.home'};
2805: $cfile = $resurl;
2806: if ($env{'form.forceedit'}) {
2807: $forceview = 1;
2808: } else {
2809: $forceedit = 1;
2810: }
2811: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2812: } else {
2813: return;
2814: }
2815: }
2816:
2817: if ($env{'request.course.id'}) {
2818: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2819: if ($group ne '') {
2820: # if this is a group homepage or group bulletin board, check group privs
2821: my $allowed = 0;
2822: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2823: if ((&allowed('mdg',$env{'request.course.id'}.
2824: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2825: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2826: $allowed = 1;
2827: }
2828: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2829: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2830: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2831: $allowed = 1;
2832: }
2833: }
2834: if ($allowed) {
2835: $home=&homeserver($cnum,$cdom);
2836: if ($env{'form.forceedit'}) {
2837: $forceview = 1;
2838: } else {
2839: $forceedit = 1;
2840: }
2841: $cfile = $resurl;
2842: } else {
2843: return;
2844: }
2845: } else {
1.1172.2.15 raeburn 2846: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2847: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2848: return;
2849: }
2850: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2851: #
2852: # No edit allowed where CC has switched to student role.
2853: #
2854: return;
2855: }
2856: }
2857: }
2858:
2859: if ($file ne '') {
2860: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2861: if (&is_course_upload($file,$cnum,$cdom)) {
2862: $uploaded = 1;
2863: $incourse = 1;
2864: if ($file =~/\.(htm|html|css|js|txt)$/) {
2865: $cfile = &hreflocation('',$file);
2866: if ($env{'form.forceedit'}) {
2867: $forceview = 1;
2868: } else {
2869: $forceedit = 1;
2870: }
2871: }
2872: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2873: $incourse = 1;
2874: if ($env{'form.forceedit'}) {
2875: $forceview = 1;
2876: } else {
2877: $forceedit = 1;
2878: }
2879: $cfile = $resurl;
2880: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2881: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2882: $incourse = 1;
2883: if ($env{'form.forceedit'}) {
2884: $forceview = 1;
2885: } else {
2886: $forceedit = 1;
2887: }
2888: $cfile = $resurl;
2889: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2890: $incourse = 1;
2891: $cfile = $resurl.'/smpedit';
2892: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2893: $incourse = 1;
2894: if ($env{'form.forceedit'}) {
2895: $forceview = 1;
2896: } else {
2897: $forceedit = 1;
2898: }
2899: $cfile = $resurl;
1.1172.2.15 raeburn 2900: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2901: $incourse = 1;
2902: if ($env{'form.forceedit'}) {
2903: $forceview = 1;
2904: } else {
2905: $forceedit = 1;
2906: }
2907: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2908: }
2909: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2910: my $template = '/res/lib/templates/simpleproblem.problem';
2911: if (&is_on_map($template)) {
2912: $incourse = 1;
2913: $forceview = 1;
2914: $cfile = $template;
2915: }
2916: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2917: $incourse = 1;
2918: if ($env{'form.forceedit'}) {
2919: $forceview = 1;
2920: } else {
2921: $forceedit = 1;
2922: }
2923: $cfile = $resurl;
2924: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2925: $incourse = 1;
2926: $forceview = 1;
2927: if ($symb) {
2928: my ($map,$id,$res)=&decode_symb($symb);
2929: $env{'request.symb'} = $symb;
2930: $cfile = &clutter($res);
2931: } else {
2932: $cfile = $env{'form.suppurl'};
2933: $cfile =~ s{^http://}{};
2934: $cfile = '/adm/wrapper/ext/'.$cfile;
2935: }
1.1172.2.31 raeburn 2936: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2937: if ($env{'form.forceedit'}) {
2938: $forceview = 1;
2939: } else {
2940: $forceedit = 1;
2941: }
2942: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2943: }
2944: }
2945: if ($uploaded || $incourse) {
2946: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2947: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2948: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2949: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2950: # Check that the user has permission to edit this resource
2951: my $setpriv = 1;
2952: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2953: if (defined($cfudom)) {
2954: $home=&homeserver($cfuname,$cfudom);
2955: $cfile=$file;
2956: }
2957: }
2958: if (($cfile ne '') && (!$incourse || $uploaded) &&
2959: (($home ne '') && ($home ne 'no_host'))) {
2960: my @ids=¤t_machine_ids();
2961: unless (grep(/^\Q$home\E$/,@ids)) {
2962: $switchserver=1;
2963: }
2964: }
2965: }
2966: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2967: }
2968:
2969: sub is_course_upload {
2970: my ($file,$cnum,$cdom) = @_;
2971: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2972: $uploadpath =~ s{^\/}{};
2973: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2974: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2975: return 1;
2976: }
2977: return;
2978: }
2979:
2980: sub in_course {
2981: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2982: if ($hideprivileged) {
2983: my $skipuser;
1.1172.2.23 raeburn 2984: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2985: my @possdoms = ($cdom);
2986: if ($coursehash{'checkforpriv'}) {
2987: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2988: }
2989: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2990: $skipuser = 1;
2991: if ($coursehash{'nothideprivileged'}) {
2992: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2993: my $user;
2994: if ($item =~ /:/) {
2995: $user = $item;
2996: } else {
2997: $user = join(':',split(/[\@]/,$item));
2998: }
2999: if ($user eq $uname.':'.$udom) {
3000: undef($skipuser);
3001: last;
3002: }
3003: }
3004: }
3005: if ($skipuser) {
3006: return 0;
3007: }
3008: }
3009: }
3010: $type ||= 'any';
3011: if (!defined($cdom) || !defined($cnum)) {
3012: my $cid = $env{'request.course.id'};
3013: $cdom = $env{'course.'.$cid.'.domain'};
3014: $cnum = $env{'course.'.$cid.'.num'};
3015: }
3016: my $typesref;
3017: if (($type eq 'any') || ($type eq 'all')) {
3018: $typesref = ['active','previous','future'];
3019: } elsif ($type eq 'previous' || $type eq 'future') {
3020: $typesref = [$type];
3021: }
3022: my %roles = &get_my_roles($uname,$udom,'userroles',
3023: $typesref,undef,[$cdom]);
3024: my ($tmp) = keys(%roles);
3025: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3026: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3027: if (@course_roles > 0) {
3028: return 1;
3029: }
3030: return 0;
3031: }
3032:
1.478 albertel 3033: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3034: # input: action, courseID, current domain, intended
1.637 raeburn 3035: # path to file, source of file, instruction to parse file for objects,
3036: # ref to hash for embedded objects,
3037: # ref to hash for codebase of java objects.
1.1095 raeburn 3038: # reference to scalar to accommodate mime type determined
3039: # from File::MMagic if $parser = parse.
1.637 raeburn 3040: #
1.485 raeburn 3041: # output: url to file (if action was uploaddoc),
3042: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3043: #
1.478 albertel 3044: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3045: # course.
1.477 raeburn 3046: #
1.478 albertel 3047: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3048: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3049: # course's home server.
1.477 raeburn 3050: #
1.478 albertel 3051: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3052: # be copied from $source (current location) to
3053: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3054: # and will then be copied to
3055: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3056: # course's home server.
1.485 raeburn 3057: #
1.481 raeburn 3058: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3059: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3060: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3061: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3062: # in course's home server.
1.637 raeburn 3063: #
1.477 raeburn 3064:
3065: sub process_coursefile {
1.1095 raeburn 3066: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3067: $mimetype)=@_;
1.477 raeburn 3068: my $fetchresult;
1.638 albertel 3069: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3070: if ($action eq 'propagate') {
1.638 albertel 3071: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3072: $home);
1.481 raeburn 3073: } else {
1.477 raeburn 3074: my $fpath = '';
3075: my $fname = $file;
1.478 albertel 3076: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3077: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3078: my $filepath = &build_filepath($fpath);
1.481 raeburn 3079: if ($action eq 'copy') {
3080: if ($source eq '') {
3081: $fetchresult = 'no source file';
3082: return $fetchresult;
3083: } else {
3084: my $destination = $filepath.'/'.$fname;
3085: rename($source,$destination);
3086: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3087: $home);
1.481 raeburn 3088: }
3089: } elsif ($action eq 'uploaddoc') {
3090: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3091: print $fh $env{'form.'.$source};
1.481 raeburn 3092: close($fh);
1.637 raeburn 3093: if ($parser eq 'parse') {
1.1024 raeburn 3094: my $mm = new File::MMagic;
1.1095 raeburn 3095: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3096: if ($type eq 'text/html') {
1.1024 raeburn 3097: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3098: unless ($parse_result eq 'ok') {
3099: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3100: }
1.637 raeburn 3101: }
1.1095 raeburn 3102: if (ref($mimetype)) {
3103: $$mimetype = $type;
3104: }
1.637 raeburn 3105: }
1.477 raeburn 3106: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3107: $home);
1.481 raeburn 3108: if ($fetchresult eq 'ok') {
3109: return '/uploaded/'.$fpath.'/'.$fname;
3110: } else {
3111: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3112: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3113: return '/adm/notfound.html';
3114: }
1.477 raeburn 3115: }
3116: }
1.485 raeburn 3117: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3118: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3119: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3120: }
3121: return $fetchresult;
3122: }
3123:
1.637 raeburn 3124: sub build_filepath {
3125: my ($fpath) = @_;
3126: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3127: unless ($fpath eq '') {
3128: my @parts=split('/',$fpath);
3129: foreach my $part (@parts) {
3130: $filepath.= '/'.$part;
3131: if ((-e $filepath)!=1) {
3132: mkdir($filepath,0777);
3133: }
3134: }
3135: }
3136: return $filepath;
3137: }
3138:
3139: sub store_edited_file {
1.638 albertel 3140: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3141: my $file = $primary_url;
3142: $file =~ s#^/uploaded/$docudom/$docuname/##;
3143: my $fpath = '';
3144: my $fname = $file;
3145: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3146: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3147: my $filepath = &build_filepath($fpath);
3148: open(my $fh,'>'.$filepath.'/'.$fname);
3149: print $fh $content;
3150: close($fh);
1.638 albertel 3151: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3152: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3153: $home);
1.637 raeburn 3154: if ($$fetchresult eq 'ok') {
3155: return '/uploaded/'.$fpath.'/'.$fname;
3156: } else {
1.638 albertel 3157: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3158: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3159: return '/adm/notfound.html';
3160: }
3161: }
3162:
1.531 albertel 3163: sub clean_filename {
1.831 albertel 3164: my ($fname,$args)=@_;
1.315 www 3165: # Replace Windows backslashes by forward slashes
1.257 www 3166: $fname=~s/\\/\//g;
1.831 albertel 3167: if (!$args->{'keep_path'}) {
3168: # Get rid of everything but the actual filename
3169: $fname=~s/^.*\/([^\/]+)$/$1/;
3170: }
1.315 www 3171: # Replace spaces by underscores
3172: $fname=~s/\s+/\_/g;
3173: # Replace all other weird characters by nothing
1.831 albertel 3174: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3175: # Replace all .\d. sequences with _\d. so they no longer look like version
3176: # numbers
3177: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3178: return $fname;
3179: }
1.1051 raeburn 3180: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3181: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3182: # image with the same aspect ratio as the original, but with dimensions which do
3183: # not exceed $resizewidth and $resizeheight.
3184:
1.984 neumanie 3185: sub resizeImage {
1.1051 raeburn 3186: my ($img_path,$resizewidth,$resizeheight) = @_;
3187: my $ima = Image::Magick->new;
3188: my $resized;
3189: if (-e $img_path) {
3190: $ima->Read($img_path);
3191: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3192: my $width = $ima->Get('width');
3193: my $height = $ima->Get('height');
3194: if ($width > $resizewidth) {
3195: my $factor = $width/$resizewidth;
3196: my $newheight = $height/$factor;
3197: $ima->Scale(width=>$resizewidth,height=>$newheight);
3198: $resized = 1;
3199: }
3200: }
3201: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3202: my $width = $ima->Get('width');
3203: my $height = $ima->Get('height');
3204: if ($height > $resizeheight) {
3205: my $factor = $height/$resizeheight;
3206: my $newwidth = $width/$factor;
3207: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3208: $resized = 1;
3209: }
3210: }
3211: if ($resized) {
3212: $ima->Write($img_path);
3213: }
3214: }
3215: return;
1.977 amueller 3216: }
3217:
1.608 albertel 3218: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3219: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3220: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3221: # $context - possible values: coursedoc, existingfile, overwrite,
3222: # canceloverwrite, or ''.
3223: # if 'coursedoc': upload to the current course
3224: # if 'existingfile': write file to tmp/overwrites directory
3225: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3226: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3227: # $subdir - directory in userfile to store the file into
1.858 raeburn 3228: # $parser - instruction to parse file for objects ($parser = parse)
3229: # $allfiles - reference to hash for embedded objects
3230: # $codebase - reference to hash for codebase of java objects
3231: # $desuname - username for permanent storage of uploaded file
3232: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3233: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3234: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3235: # $resizewidth - width (pixels) to which to resize uploaded image
3236: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3237: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3238: # from File::MMagic.
1.858 raeburn 3239: #
1.686 albertel 3240: # output: url of file in userspace, or error: <message>
3241: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3242:
1.531 albertel 3243: sub userfileupload {
1.1090 raeburn 3244: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3245: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3246: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3247: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3248: $fname=&clean_filename($fname);
1.1090 raeburn 3249: # See if there is anything left
1.257 www 3250: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3251: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3252: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3253: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3254: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3255: my $now = time;
1.1090 raeburn 3256: my $filepath;
1.1095 raeburn 3257: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3258: $filepath = 'tmp/helprequests/'.$now;
3259: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3260: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3261: '_'.$env{'user.domain'}.'/pending';
3262: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3263: my ($docuname,$docudom);
3264: if ($destudom) {
3265: $docudom = $destudom;
3266: } else {
3267: $docudom = $env{'user.domain'};
3268: }
3269: if ($destuname) {
3270: $docuname = $destuname;
3271: } else {
3272: $docuname = $env{'user.name'};
3273: }
3274: if (exists($env{'form.group'})) {
3275: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3276: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3277: }
3278: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3279: if ($context eq 'canceloverwrite') {
3280: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3281: if (-e $tempfile) {
3282: my @info = stat($tempfile);
3283: if ($info[9] eq $env{'form.timestamp'}) {
3284: unlink($tempfile);
3285: }
3286: }
3287: return;
1.523 raeburn 3288: }
3289: }
1.1090 raeburn 3290: # Create the directory if not present
1.741 raeburn 3291: my @parts=split(/\//,$filepath);
3292: my $fullpath = $perlvar{'lonDaemons'};
3293: for (my $i=0;$i<@parts;$i++) {
3294: $fullpath .= '/'.$parts[$i];
3295: if ((-e $fullpath)!=1) {
3296: mkdir($fullpath,0777);
3297: }
3298: }
3299: open(my $fh,'>'.$fullpath.'/'.$fname);
3300: print $fh $env{'form.'.$formname};
3301: close($fh);
1.1090 raeburn 3302: if ($context eq 'existingfile') {
3303: my @info = stat($fullpath.'/'.$fname);
3304: return ($fullpath.'/'.$fname,$info[9]);
3305: } else {
3306: return $fullpath.'/'.$fname;
3307: }
1.523 raeburn 3308: }
1.995 raeburn 3309: if ($subdir eq 'scantron') {
3310: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3311: } else {
1.995 raeburn 3312: $fname="$subdir/$fname";
3313: }
1.1090 raeburn 3314: if ($context eq 'coursedoc') {
1.638 albertel 3315: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3316: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3317: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3318: return &finishuserfileupload($docuname,$docudom,
3319: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3320: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3321: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3322: } else {
1.1172.2.21 raeburn 3323: if ($env{'form.folder'}) {
3324: $fname=$env{'form.folder'}.'/'.$fname;
3325: }
1.638 albertel 3326: return &process_coursefile('uploaddoc',$docuname,$docudom,
3327: $fname,$formname,$parser,
1.1095 raeburn 3328: $allfiles,$codebase,$mimetype);
1.481 raeburn 3329: }
1.719 banghart 3330: } elsif (defined($destuname)) {
3331: my $docuname=$destuname;
3332: my $docudom=$destudom;
1.860 raeburn 3333: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3334: $parser,$allfiles,$codebase,
1.1051 raeburn 3335: $thumbwidth,$thumbheight,
1.1095 raeburn 3336: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3337: } else {
1.638 albertel 3338: my $docuname=$env{'user.name'};
3339: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3340: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3341: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3342: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3343: }
1.860 raeburn 3344: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3345: $parser,$allfiles,$codebase,
1.1051 raeburn 3346: $thumbwidth,$thumbheight,
1.1095 raeburn 3347: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3348: }
1.271 www 3349: }
3350:
3351: sub finishuserfileupload {
1.860 raeburn 3352: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3353: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3354: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3355: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3356:
1.860 raeburn 3357: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3358: $file=$fname;
3359: if ($fname=~m|/|) {
3360: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3361: $path.=$fnamepath.'/';
3362: }
1.259 www 3363: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3364: my $count;
3365: for ($count=4;$count<=$#parts;$count++) {
3366: $filepath.="/$parts[$count]";
3367: if ((-e $filepath)!=1) {
3368: mkdir($filepath,0777);
3369: }
3370: }
1.984 neumanie 3371:
1.258 www 3372: # Save the file
3373: {
1.701 albertel 3374: if (!open(FH,'>'.$filepath.'/'.$file)) {
3375: &logthis('Failed to create '.$filepath.'/'.$file);
3376: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3377: return '/adm/notfound.html';
3378: }
1.1090 raeburn 3379: if ($context eq 'overwrite') {
1.1117 foxr 3380: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3381: my $target = $filepath.'/'.$file;
3382: if (-e $source) {
3383: my @info = stat($source);
3384: if ($info[9] eq $env{'form.timestamp'}) {
3385: unless (&File::Copy::move($source,$target)) {
3386: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3387: return "Moving from $source failed";
3388: }
3389: } else {
3390: return "Temporary file: $source had unexpected date/time for last modification";
3391: }
3392: } else {
3393: return "Temporary file: $source missing";
3394: }
3395: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3396: &logthis('Failed to write to '.$filepath.'/'.$file);
3397: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3398: return '/adm/notfound.html';
3399: }
1.570 albertel 3400: close(FH);
1.1051 raeburn 3401: if ($resizewidth && $resizeheight) {
3402: my $mm = new File::MMagic;
3403: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3404: if ($mime_type =~ m{^image/}) {
3405: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3406: }
1.977 amueller 3407: }
1.258 www 3408: }
1.1152 raeburn 3409: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3410: if (ref($mimetype)) {
3411: if ($$mimetype eq '') {
3412: my $mm = new File::MMagic;
3413: my $type = $mm->checktype_filename($filepath.'/'.$file);
3414: $$mimetype = $type;
3415: }
3416: }
3417: }
1.637 raeburn 3418: if ($parser eq 'parse') {
1.1152 raeburn 3419: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3420: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3421: $allfiles,$codebase);
3422: unless ($parse_result eq 'ok') {
3423: &logthis('Failed to parse '.$filepath.$file.
3424: ' for embedded media: '.$parse_result);
3425: }
1.637 raeburn 3426: }
3427: }
1.860 raeburn 3428: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3429: my $input = $filepath.'/'.$file;
3430: my $output = $filepath.'/'.'tn-'.$file;
3431: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3432: system("convert -sample $thumbsize $input $output");
3433: if (-e $filepath.'/'.'tn-'.$file) {
3434: $fetchthumb = 1;
3435: }
3436: }
1.858 raeburn 3437:
1.259 www 3438: # Notify homeserver to grep it
3439: #
1.984 neumanie 3440: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3441: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3442: if ($fetchresult eq 'ok') {
1.860 raeburn 3443: if ($fetchthumb) {
3444: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3445: if ($thumbresult ne 'ok') {
3446: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3447: $docuhome.': '.$thumbresult);
3448: }
3449: }
1.259 www 3450: #
1.258 www 3451: # Return the URL to it
1.494 albertel 3452: return '/uploaded/'.$path.$file;
1.263 www 3453: } else {
1.494 albertel 3454: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3455: ': '.$fetchresult);
1.263 www 3456: return '/adm/notfound.html';
1.858 raeburn 3457: }
1.493 albertel 3458: }
3459:
1.637 raeburn 3460: sub extract_embedded_items {
1.961 raeburn 3461: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3462: my @state = ();
1.1164 raeburn 3463: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3464: my %javafiles = (
3465: codebase => '',
3466: code => '',
3467: archive => ''
3468: );
3469: my %mediafiles = (
3470: src => '',
3471: movie => '',
3472: );
1.648 raeburn 3473: my $p;
3474: if ($content) {
3475: $p = HTML::LCParser->new($content);
3476: } else {
1.961 raeburn 3477: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3478: }
1.641 albertel 3479: while (my $t=$p->get_token()) {
1.640 albertel 3480: if ($t->[0] eq 'S') {
3481: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3482: push(@state, $tagname);
1.648 raeburn 3483: if (lc($tagname) eq 'allow') {
3484: &add_filetype($allfiles,$attr->{'src'},'src');
3485: }
1.640 albertel 3486: if (lc($tagname) eq 'img') {
3487: &add_filetype($allfiles,$attr->{'src'},'src');
3488: }
1.886 albertel 3489: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3490: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3491: &add_filetype($allfiles,$attr->{'href'},'href');
3492: }
1.886 albertel 3493: }
1.645 raeburn 3494: if (lc($tagname) eq 'script') {
1.1164 raeburn 3495: my $src;
1.645 raeburn 3496: if ($attr->{'archive'} =~ /\.jar$/i) {
3497: &add_filetype($allfiles,$attr->{'archive'},'archive');
3498: } else {
1.1164 raeburn 3499: if ($attr->{'src'} ne '') {
3500: $src = $attr->{'src'};
3501: &add_filetype($allfiles,$src,'src');
3502: }
3503: }
3504: my $text = $p->get_trimmed_text();
3505: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3506: my @swfargs = split(/,/,$1);
3507: foreach my $item (@swfargs) {
3508: $item =~ s/["']//g;
3509: $item =~ s/^\s+//;
3510: $item =~ s/\s+$//;
3511: }
3512: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3513: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3514: push(@{$related{$swfargs[0]}},$swfargs[2]);
3515: } else {
3516: $related{$swfargs[0]} = [$swfargs[2]];
3517: }
3518: }
1.645 raeburn 3519: }
3520: }
3521: if (lc($tagname) eq 'link') {
3522: if (lc($attr->{'rel'}) eq 'stylesheet') {
3523: &add_filetype($allfiles,$attr->{'href'},'href');
3524: }
3525: }
1.640 albertel 3526: if (lc($tagname) eq 'object' ||
3527: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3528: foreach my $item (keys(%javafiles)) {
3529: $javafiles{$item} = '';
3530: }
1.1164 raeburn 3531: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3532: $lastids{lc($tagname)} = $attr->{'id'};
3533: }
1.640 albertel 3534: }
3535: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3536: my $name = lc($attr->{'name'});
3537: foreach my $item (keys(%javafiles)) {
3538: if ($name eq $item) {
3539: $javafiles{$item} = $attr->{'value'};
3540: last;
3541: }
3542: }
1.1164 raeburn 3543: my $pathfrom;
1.640 albertel 3544: foreach my $item (keys(%mediafiles)) {
3545: if ($name eq $item) {
1.1164 raeburn 3546: $pathfrom = $attr->{'value'};
3547: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3548: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3549: last;
3550: }
3551: }
1.1164 raeburn 3552: if ($name eq 'flashvars') {
3553: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3554: }
3555: if ($pathfrom ne '') {
3556: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3557: $pathfrom);
3558: }
1.640 albertel 3559: }
3560: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3561: foreach my $item (keys(%javafiles)) {
3562: if ($attr->{$item}) {
3563: $javafiles{$item} = $attr->{$item};
3564: last;
3565: }
3566: }
3567: foreach my $item (keys(%mediafiles)) {
3568: if ($attr->{$item}) {
3569: &add_filetype($allfiles,$attr->{$item},$item);
3570: last;
3571: }
3572: }
1.1164 raeburn 3573: if (lc($tagname) eq 'embed') {
3574: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3575: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3576: $attr->{'src'});
3577: }
3578: }
1.640 albertel 3579: }
1.1172.2.35 raeburn 3580: if (lc($tagname) eq 'iframe') {
3581: my $src = $attr->{'src'} ;
3582: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3583: &add_filetype($allfiles,$src,'src');
3584: } elsif ($src =~ m{^/}) {
3585: if ($env{'request.course.id'}) {
3586: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3587: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3588: my $url = &hreflocation('',$fullpath);
3589: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3590: my $relpath = $1;
3591: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3592: &add_filetype($allfiles,$1,'src');
3593: }
3594: }
3595: }
3596: }
3597: }
1.1164 raeburn 3598: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3599: pop(@state);
1.1164 raeburn 3600: }
1.640 albertel 3601: } elsif ($t->[0] eq 'E') {
3602: my ($tagname) = ($t->[1]);
3603: if ($javafiles{'codebase'} ne '') {
3604: $javafiles{'codebase'} .= '/';
3605: }
3606: if (lc($tagname) eq 'applet' ||
3607: lc($tagname) eq 'object' ||
3608: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3609: ) {
3610: foreach my $item (keys(%javafiles)) {
3611: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3612: my $file=$javafiles{'codebase'}.$javafiles{$item};
3613: &add_filetype($allfiles,$file,$item);
3614: }
3615: }
3616: }
3617: pop @state;
3618: }
3619: }
1.1164 raeburn 3620: foreach my $id (sort(keys(%flashvars))) {
3621: if ($shockwave{$id} ne '') {
3622: my @pairs = split(/\&/,$flashvars{$id});
3623: foreach my $pair (@pairs) {
3624: my ($key,$value) = split(/\=/,$pair);
3625: if ($key eq 'thumb') {
3626: &add_filetype($allfiles,$value,$key);
3627: } elsif ($key eq 'content') {
3628: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3629: my ($ext) = ($value =~ /\.([^.]+)$/);
3630: if ($ext ne '') {
3631: &add_filetype($allfiles,$path.$value,$ext);
3632: }
3633: }
3634: }
3635: }
3636: }
1.637 raeburn 3637: return 'ok';
3638: }
3639:
1.639 albertel 3640: sub add_filetype {
3641: my ($allfiles,$file,$type)=@_;
3642: if (exists($allfiles->{$file})) {
3643: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3644: push(@{$allfiles->{$file}}, &escape($type));
3645: }
3646: } else {
3647: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3648: }
3649: }
3650:
1.1164 raeburn 3651: sub embedded_dependency {
3652: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3653: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3654: if (($identifier ne '') &&
3655: (ref($related->{$identifier}) eq 'ARRAY') &&
3656: ($pathfrom ne '')) {
3657: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3658: foreach my $dep (@{$related->{$identifier}}) {
3659: &add_filetype($allfiles,$path.$dep,'object');
3660: }
3661: }
3662: }
3663: return;
3664: }
3665:
1.493 albertel 3666: sub removeuploadedurl {
1.984 neumanie 3667: my ($url)=@_;
3668: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3669: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3670: }
3671:
3672: sub removeuserfile {
3673: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3674: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3675: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3676: if ($result eq 'ok') {
1.798 raeburn 3677: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3678: my $metafile = $fname.'.meta';
3679: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3680: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3681: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3682: my $sqlresult =
1.823 albertel 3683: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3684: 'portfolio_metadata',$group,
3685: 'delete');
1.798 raeburn 3686: }
3687: }
3688: return $result;
1.257 www 3689: }
1.15 www 3690:
1.530 albertel 3691: sub mkdiruserfile {
3692: my ($docuname,$docudom,$dir)=@_;
3693: my $home=&homeserver($docuname,$docudom);
3694: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3695: }
3696:
1.531 albertel 3697: sub renameuserfile {
3698: my ($docuname,$docudom,$old,$new)=@_;
3699: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3700: my $result = &reply("renameuserfile:$docudom:$docuname:".
3701: &escape("$old").':'.&escape("$new"),$home);
3702: if ($result eq 'ok') {
3703: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3704: my $oldmeta = $old.'.meta';
3705: my $newmeta = $new.'.meta';
3706: my $metaresult =
3707: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3708: my $url = "/uploaded/$docudom/$docuname/$old";
3709: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3710: my $sqlresult =
1.823 albertel 3711: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3712: 'portfolio_metadata',$group,
3713: 'delete');
1.798 raeburn 3714: }
3715: }
3716: return $result;
1.531 albertel 3717: }
3718:
1.14 www 3719: # ------------------------------------------------------------------------- Log
3720:
3721: sub log {
3722: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3723: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3724: }
3725:
3726: # ------------------------------------------------------------------ Course Log
1.352 www 3727: #
3728: # This routine flushes several buffers of non-mission-critical nature
3729: #
1.157 www 3730:
3731: sub flushcourselogs {
1.352 www 3732: &logthis('Flushing log buffers');
3733: #
3734: # course logs
3735: # This is a log of all transactions in a course, which can be used
3736: # for data mining purposes
3737: #
3738: # It also collects the courseid database, which lists last transaction
3739: # times and course titles for all courseids
3740: #
3741: my %courseidbuffer=();
1.921 raeburn 3742: foreach my $crsid (keys(%courselogs)) {
1.352 www 3743: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3744: &escape($courselogs{$crsid}),
3745: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3746: delete $courselogs{$crsid};
3747: } else {
3748: &logthis('Failed to flush log buffer for '.$crsid);
3749: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3750: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3751: " exceeded maximum size, deleting.</font>");
3752: delete $courselogs{$crsid};
3753: }
1.352 www 3754: }
1.920 raeburn 3755: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3756: 'description' => $coursedescrbuf{$crsid},
3757: 'inst_code' => $courseinstcodebuf{$crsid},
3758: 'type' => $coursetypebuf{$crsid},
3759: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3760: };
1.191 harris41 3761: }
1.352 www 3762: #
3763: # Write course id database (reverse lookup) to homeserver of courses
3764: # Is used in pickcourse
3765: #
1.840 albertel 3766: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3767: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3768: $courseidbuffer{$crs_home},
3769: $crs_home,'timeonly');
1.352 www 3770: }
3771: #
3772: # File accesses
3773: # Writes to the dynamic metadata of resources to get hit counts, etc.
3774: #
1.449 matthew 3775: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3776: if ($entry =~ /___count$/) {
3777: my ($dom,$name);
1.807 albertel 3778: ($dom,$name,undef)=
1.811 albertel 3779: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3780: if (! defined($dom) || $dom eq '' ||
3781: ! defined($name) || $name eq '') {
1.620 albertel 3782: my $cid = $env{'request.course.id'};
3783: $dom = $env{'request.'.$cid.'.domain'};
3784: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3785: }
1.450 matthew 3786: my $value = $accesshash{$entry};
3787: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3788: my %temphash=($url => $value);
1.449 matthew 3789: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3790: if ($result eq 'ok') {
3791: delete $accesshash{$entry};
3792: }
3793: } else {
1.811 albertel 3794: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3795: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3796: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3797: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3798: delete $accesshash{$entry};
3799: }
1.185 www 3800: }
1.191 harris41 3801: }
1.352 www 3802: #
3803: # Roles
3804: # Reverse lookup of user roles for course faculty/staff and co-authorship
3805: #
1.800 albertel 3806: foreach my $entry (keys(%userrolehash)) {
1.351 www 3807: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3808: split(/\:/,$entry);
3809: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3810: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3811: $rudom,$runame) eq 'ok') {
3812: delete $userrolehash{$entry};
3813: }
3814: }
1.662 raeburn 3815: #
3816: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3817: #
3818: my %domrolebuffer = ();
1.1000 raeburn 3819: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3820: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3821: if ($domrolebuffer{$rudom}) {
3822: $domrolebuffer{$rudom}.='&'.&escape($entry).
3823: '='.&escape($domainrolehash{$entry});
3824: } else {
3825: $domrolebuffer{$rudom}.=&escape($entry).
3826: '='.&escape($domainrolehash{$entry});
3827: }
3828: delete $domainrolehash{$entry};
3829: }
3830: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3831: my %servers = &get_servers($dom,'library');
3832: foreach my $tryserver (keys(%servers)) {
3833: unless (&reply('domroleput:'.$dom.':'.
3834: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3835: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3836: }
1.662 raeburn 3837: }
3838: }
1.186 www 3839: $dumpcount++;
1.157 www 3840: }
3841:
3842: sub courselog {
3843: my $what=shift;
1.158 www 3844: $what=time.':'.$what;
1.620 albertel 3845: unless ($env{'request.course.id'}) { return ''; }
3846: $coursedombuf{$env{'request.course.id'}}=
3847: $env{'course.'.$env{'request.course.id'}.'.domain'};
3848: $coursenumbuf{$env{'request.course.id'}}=
3849: $env{'course.'.$env{'request.course.id'}.'.num'};
3850: $coursehombuf{$env{'request.course.id'}}=
3851: $env{'course.'.$env{'request.course.id'}.'.home'};
3852: $coursedescrbuf{$env{'request.course.id'}}=
3853: $env{'course.'.$env{'request.course.id'}.'.description'};
3854: $courseinstcodebuf{$env{'request.course.id'}}=
3855: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3856: $courseownerbuf{$env{'request.course.id'}}=
3857: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3858: $coursetypebuf{$env{'request.course.id'}}=
3859: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3860: if (defined $courselogs{$env{'request.course.id'}}) {
3861: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3862: } else {
1.620 albertel 3863: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3864: }
1.620 albertel 3865: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3866: &flushcourselogs();
3867: }
1.158 www 3868: }
3869:
3870: sub courseacclog {
3871: my $fnsymb=shift;
1.620 albertel 3872: unless ($env{'request.course.id'}) { return ''; }
3873: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3874: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3875: $what.=':POST';
1.583 matthew 3876: # FIXME: Probably ought to escape things....
1.800 albertel 3877: foreach my $key (keys(%env)) {
3878: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3879: my $formitem = $1;
3880: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3881: $what.=':'.$formitem.'='.$env{$key};
3882: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3883: $what.=':'.$formitem.'='.$env{$key};
3884: }
1.158 www 3885: }
1.191 harris41 3886: }
1.583 matthew 3887: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3888: # FIXME: We should not be depending on a form parameter that someone
3889: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3890: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3891: $what.= ':POST';
3892: # FIXME: Probably ought to escape things....
3893: foreach my $element ('courseexp','crsfulltext','crsrelated',
3894: 'crsdiscuss') {
1.620 albertel 3895: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3896: }
3897: }
1.158 www 3898: }
3899: &courselog($what);
1.149 www 3900: }
3901:
1.185 www 3902: sub countacc {
3903: my $url=&declutter(shift);
1.458 matthew 3904: return if (! defined($url) || $url eq '');
1.620 albertel 3905: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3906: #
3907: # Mark that this url was used in this course
3908: #
1.620 albertel 3909: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3910: #
3911: # Increase the access count for this resource in this child process
3912: #
1.281 www 3913: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3914: $accesshash{$key}++;
1.185 www 3915: }
1.349 www 3916:
1.361 www 3917: sub linklog {
3918: my ($from,$to)=@_;
3919: $from=&declutter($from);
3920: $to=&declutter($to);
3921: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3922: $accesshash{$to.'___'.$from.'___goto'}=1;
3923: }
1.1160 www 3924:
3925: sub statslog {
3926: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3927: if ($users<2) { return; }
3928: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3929: 'course' => $env{'request.course.id'},
3930: 'sections' => '"all"',
3931: 'num_students' => $users,
3932: 'part' => $part,
3933: 'symb' => $symb,
3934: 'mean_tries' => $av_attempts,
3935: 'deg_of_diff' => $degdiff});
3936: foreach my $key (keys(%dynstore)) {
3937: $accesshash{$key}=$dynstore{$key};
3938: }
3939: }
1.361 www 3940:
1.349 www 3941: sub userrolelog {
3942: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3943: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3944: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3945: $userrolehash
3946: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3947: =$tend.':'.$tstart;
1.662 raeburn 3948: }
1.1169 droeschl 3949: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3950: $userrolehash
3951: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3952: =$tend.':'.$tstart;
3953: }
1.1169 droeschl 3954: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3955: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3956: $domainrolehash
3957: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3958: = $tend.':'.$tstart;
3959: }
1.351 www 3960: }
3961:
1.957 raeburn 3962: sub courserolelog {
3963: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3964: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3965: my $cdom = $1;
3966: my $cnum = $2;
3967: my $sec = $3;
3968: my $namespace = 'rolelog';
3969: my %storehash = (
3970: role => $trole,
3971: start => $tstart,
3972: end => $tend,
3973: selfenroll => $selfenroll,
3974: context => $context,
3975: );
3976: if ($trole eq 'gr') {
3977: $namespace = 'groupslog';
3978: $storehash{'group'} = $sec;
3979: } else {
3980: $storehash{'section'} = $sec;
3981: }
3982: &write_log('course',$namespace,\%storehash,$delflag,$username,
3983: $domain,$cnum,$cdom);
3984: if (($trole ne 'st') || ($sec ne '')) {
3985: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3986: }
3987: }
3988: return;
3989: }
3990:
1.1172.2.9 raeburn 3991: sub domainrolelog {
3992: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3993: if ($area =~ m{^/($match_domain)/$}) {
3994: my $cdom = $1;
3995: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3996: my $namespace = 'rolelog';
3997: my %storehash = (
3998: role => $trole,
3999: start => $tstart,
4000: end => $tend,
4001: context => $context,
4002: );
4003: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4004: $domain,$domconfiguser,$cdom);
4005: }
4006: return;
4007:
4008: }
4009:
4010: sub coauthorrolelog {
4011: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4012: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4013: my $audom = $1;
4014: my $auname = $2;
4015: my $namespace = 'rolelog';
4016: my %storehash = (
4017: role => $trole,
4018: start => $tstart,
4019: end => $tend,
4020: context => $context,
4021: );
4022: &write_log('author',$namespace,\%storehash,$delflag,$username,
4023: $domain,$auname,$audom);
4024: }
4025: return;
4026: }
4027:
1.351 www 4028: sub get_course_adv_roles {
1.948 raeburn 4029: my ($cid,$codes) = @_;
1.620 albertel 4030: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4031: my %coursehash=&coursedescription($cid);
1.988 raeburn 4032: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4033: my %nothide=();
1.800 albertel 4034: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4035: if ($user !~ /:/) {
4036: $nothide{join(':',split(/[\@]/,$user))}=1;
4037: } else {
4038: $nothide{$user}=1;
4039: }
1.470 www 4040: }
1.1172.2.23 raeburn 4041: my @possdoms = ($coursehash{'domain'});
4042: if ($coursehash{'checkforpriv'}) {
4043: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4044: }
1.351 www 4045: my %returnhash=();
4046: my %dumphash=
4047: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4048: my $now=time;
1.997 raeburn 4049: my %privileged;
1.1000 raeburn 4050: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4051: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4052: if (($tstart) && ($tstart<0)) { next; }
4053: if (($tend) && ($tend<$now)) { next; }
4054: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4055: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4056: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4057: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4058: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4059: if ($role eq 'cr') { next; }
1.948 raeburn 4060: if ($codes) {
4061: if ($section) { $role .= ':'.$section; }
4062: if ($returnhash{$role}) {
4063: $returnhash{$role}.=','.$username.':'.$domain;
4064: } else {
4065: $returnhash{$role}=$username.':'.$domain;
4066: }
1.351 www 4067: } else {
1.988 raeburn 4068: my $key=&plaintext($role,$crstype);
1.973 bisitz 4069: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4070: if ($returnhash{$key}) {
4071: $returnhash{$key}.=','.$username.':'.$domain;
4072: } else {
4073: $returnhash{$key}=$username.':'.$domain;
4074: }
1.351 www 4075: }
1.948 raeburn 4076: }
1.400 www 4077: return %returnhash;
4078: }
4079:
4080: sub get_my_roles {
1.937 raeburn 4081: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4082: unless (defined($uname)) { $uname=$env{'user.name'}; }
4083: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4084: my (%dumphash,%nothide);
1.1086 raeburn 4085: if ($context eq 'userroles') {
1.1166 raeburn 4086: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4087: } else {
1.1172.2.23 raeburn 4088: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4089: if ($hidepriv) {
4090: my %coursehash=&coursedescription($udom.'_'.$uname);
4091: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4092: if ($user !~ /:/) {
4093: $nothide{join(':',split(/[\@]/,$user))} = 1;
4094: } else {
4095: $nothide{$user} = 1;
4096: }
4097: }
4098: }
1.858 raeburn 4099: }
1.400 www 4100: my %returnhash=();
4101: my $now=time;
1.999 raeburn 4102: my %privileged;
1.800 albertel 4103: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4104: my ($role,$tend,$tstart);
4105: if ($context eq 'userroles') {
1.1149 raeburn 4106: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4107: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4108: } else {
4109: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4110: }
1.400 www 4111: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4112: my $status = 'active';
1.939 raeburn 4113: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4114: $status = 'previous';
4115: }
4116: if (($tstart) && ($now<$tstart)) {
4117: $status = 'future';
4118: }
4119: if (ref($types) eq 'ARRAY') {
4120: if (!grep(/^\Q$status\E$/,@{$types})) {
4121: next;
4122: }
4123: } else {
4124: if ($status ne 'active') {
4125: next;
4126: }
4127: }
1.867 raeburn 4128: my ($rolecode,$username,$domain,$section,$area);
4129: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4130: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4131: (undef,$domain,$username,$section) = split(/\//,$area);
4132: } else {
4133: ($role,$username,$domain,$section) = split(/\:/,$entry);
4134: }
1.832 raeburn 4135: if (ref($roledoms) eq 'ARRAY') {
4136: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4137: next;
4138: }
4139: }
4140: if (ref($roles) eq 'ARRAY') {
4141: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4142: if ($role =~ /^cr\//) {
4143: if (!grep(/^cr$/,@{$roles})) {
4144: next;
4145: }
1.1104 raeburn 4146: } elsif ($role =~ /^gr\//) {
4147: if (!grep(/^gr$/,@{$roles})) {
4148: next;
4149: }
1.922 raeburn 4150: } else {
4151: next;
4152: }
1.832 raeburn 4153: }
1.867 raeburn 4154: }
1.937 raeburn 4155: if ($hidepriv) {
1.1172.2.23 raeburn 4156: my @privroles = ('dc','su');
1.999 raeburn 4157: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4158: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4159: } else {
1.1172.2.23 raeburn 4160: my $possdoms = [$domain];
4161: if (ref($roledoms) eq 'ARRAY') {
4162: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4163: }
1.1172.2.23 raeburn 4164: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4165: if (!$nothide{$username.':'.$domain}) {
4166: next;
4167: }
4168: }
1.937 raeburn 4169: }
4170: }
1.933 raeburn 4171: if ($withsec) {
4172: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4173: $tstart.':'.$tend;
4174: } else {
4175: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4176: }
1.832 raeburn 4177: }
1.373 www 4178: return %returnhash;
1.399 www 4179: }
4180:
4181: # ----------------------------------------------------- Frontpage Announcements
4182: #
4183: #
4184:
4185: sub postannounce {
4186: my ($server,$text)=@_;
1.844 albertel 4187: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4188: unless ($text=~/\w/) { $text=''; }
4189: return &reply('setannounce:'.&escape($text),$server);
4190: }
4191:
4192: sub getannounce {
1.448 albertel 4193:
4194: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4195: my $announcement='';
1.800 albertel 4196: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4197: close($fh);
1.399 www 4198: if ($announcement=~/\w/) {
4199: return
4200: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4201: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4202: } else {
4203: return '';
4204: }
4205: } else {
4206: return '';
4207: }
1.351 www 4208: }
1.353 www 4209:
4210: # ---------------------------------------------------------- Course ID routines
4211: # Deal with domain's nohist_courseid.db files
4212: #
4213:
4214: sub courseidput {
1.921 raeburn 4215: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4216: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4217: my $outcome;
4218: if ($caller eq 'timeonly') {
4219: my $cids = '';
4220: foreach my $item (keys(%$storehash)) {
4221: $cids.=&escape($item).'&';
4222: }
4223: $cids=~s/\&$//;
4224: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4225: $coursehome);
4226: } else {
4227: my $items = '';
4228: foreach my $item (keys(%$storehash)) {
4229: $items.= &escape($item).'='.
4230: &freeze_escape($$storehash{$item}).'&';
4231: }
4232: $items=~s/\&$//;
4233: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4234: $coursehome);
1.918 raeburn 4235: }
4236: if ($outcome eq 'unknown_cmd') {
4237: my $what;
4238: foreach my $cid (keys(%$storehash)) {
4239: $what .= &escape($cid).'=';
1.921 raeburn 4240: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4241: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4242: }
4243: $what =~ s/\:$/&/;
4244: }
4245: $what =~ s/\&$//;
4246: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4247: } else {
4248: return $outcome;
4249: }
1.353 www 4250: }
4251:
4252: sub courseiddump {
1.921 raeburn 4253: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4254: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4255: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4256: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4257: $hasuniquecode)=@_;
1.918 raeburn 4258: my $as_hash = 1;
4259: my %returnhash;
4260: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4261: my %libserv = &all_library();
4262: foreach my $tryserver (keys(%libserv)) {
4263: if ( ( $hostidflag == 1
4264: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4265: || (!defined($hostidflag)) ) {
4266:
1.918 raeburn 4267: if (($domfilter eq '') ||
4268: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4269: my $rep;
4270: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4271: $rep = &LONCAPA::Lond::dump_course_id_handler(
4272: join(":", (&host_domain($tryserver), $sincefilter,
4273: &escape($descfilter), &escape($instcodefilter),
4274: &escape($ownerfilter), &escape($coursefilter),
4275: &escape($typefilter), &escape($regexp_ok),
4276: $as_hash, &escape($selfenrollonly),
4277: &escape($catfilter), $showhidden, $caller,
4278: &escape($cloner), &escape($cc_clone), $cloneonly,
4279: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4280: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4281: } else {
4282: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4283: $sincefilter.':'.&escape($descfilter).':'.
4284: &escape($instcodefilter).':'.&escape($ownerfilter).
4285: ':'.&escape($coursefilter).':'.&escape($typefilter).
4286: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4287: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4288: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4289: &escape($cc_clone).':'.$cloneonly.':'.
4290: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4291: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4292: $tryserver);
4293: }
4294:
1.918 raeburn 4295: my @pairs=split(/\&/,$rep);
4296: foreach my $item (@pairs) {
4297: my ($key,$value)=split(/\=/,$item,2);
4298: $key = &unescape($key);
4299: next if ($key =~ /^error: 2 /);
4300: my $result = &thaw_unescape($value);
4301: if (ref($result) eq 'HASH') {
4302: $returnhash{$key}=$result;
4303: } else {
1.921 raeburn 4304: my @responses = split(/:/,$value);
4305: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4306: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4307: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4308: }
1.1008 raeburn 4309: }
1.353 www 4310: }
4311: }
4312: }
4313: }
4314: return %returnhash;
4315: }
4316:
1.1055 raeburn 4317: sub courselastaccess {
4318: my ($cdom,$cnum,$hostidref) = @_;
4319: my %returnhash;
4320: if ($cdom && $cnum) {
4321: my $chome = &homeserver($cnum,$cdom);
4322: if ($chome ne 'no_host') {
4323: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4324: &extract_lastaccess(\%returnhash,$rep);
4325: }
4326: } else {
4327: if (!$cdom) { $cdom=''; }
4328: my %libserv = &all_library();
4329: foreach my $tryserver (keys(%libserv)) {
4330: if (ref($hostidref) eq 'ARRAY') {
4331: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4332: }
4333: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4334: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4335: &extract_lastaccess(\%returnhash,$rep);
4336: }
4337: }
4338: }
4339: return %returnhash;
4340: }
4341:
4342: sub extract_lastaccess {
4343: my ($returnhash,$rep) = @_;
4344: if (ref($returnhash) eq 'HASH') {
4345: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4346: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4347: $rep eq '') {
4348: my @pairs=split(/\&/,$rep);
4349: foreach my $item (@pairs) {
4350: my ($key,$value)=split(/\=/,$item,2);
4351: $key = &unescape($key);
4352: next if ($key =~ /^error: 2 /);
4353: $returnhash->{$key} = &thaw_unescape($value);
4354: }
4355: }
4356: }
4357: return;
4358: }
4359:
1.658 raeburn 4360: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4361:
4362: sub dcmailput {
1.685 raeburn 4363: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4364: my $status = &Apache::lonnet::critical(
1.740 www 4365: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4366: &escape($message),$server);
1.662 raeburn 4367: return $status;
4368: }
4369:
1.658 raeburn 4370: sub dcmaildump {
4371: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4372: my %returnhash=();
1.846 albertel 4373:
4374: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4375: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4376: &escape($enddate).':';
4377: my @esc_senders=map { &escape($_)} @$senders;
4378: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4379: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4380: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4381: if (($key) && ($value)) {
4382: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4383: }
4384: }
4385: }
4386: return %returnhash;
4387: }
1.662 raeburn 4388: # ---------------------------------------------------------- Domain roles
4389:
4390: sub get_domain_roles {
4391: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4392: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4393: $startdate = '.';
4394: }
1.1018 raeburn 4395: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4396: $enddate = '.';
4397: }
1.922 raeburn 4398: my $rolelist;
4399: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4400: $rolelist = join('&',@{$roles});
1.922 raeburn 4401: }
1.662 raeburn 4402: my %personnel = ();
1.841 albertel 4403:
4404: my %servers = &get_servers($dom,'library');
4405: foreach my $tryserver (keys(%servers)) {
4406: %{$personnel{$tryserver}}=();
4407: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4408: &escape($startdate).':'.
4409: &escape($enddate).':'.
4410: &escape($rolelist), $tryserver))) {
4411: my ($key,$value) = split(/\=/,$line,2);
4412: if (($key) && ($value)) {
4413: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4414: }
4415: }
1.662 raeburn 4416: }
4417: return %personnel;
4418: }
1.658 raeburn 4419:
1.1057 www 4420: # ----------------------------------------------------------- Interval timing
1.149 www 4421:
1.1153 www 4422: {
4423: # Caches needed for speedup of navmaps
4424: # We don't want to cache this for very long at all (5 seconds at most)
4425: #
4426: # The user for whom we cache
4427: my $cachedkey='';
4428: # The cached times for this user
4429: my %cachedtimes=();
4430: # When this was last done
4431: my $cachedtime=();
4432:
4433: sub load_all_first_access {
1.1154 raeburn 4434: my ($uname,$udom)=@_;
1.1156 www 4435: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4436: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4437: return;
4438: }
4439: $cachedtime=time;
4440: $cachedkey=$uname.':'.$udom;
4441: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4442: }
4443:
1.504 albertel 4444: sub get_first_access {
1.1162 raeburn 4445: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4446: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4447: if ($argsymb) { $symb=$argsymb; }
4448: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4449: if ($argmap) { $map = $argmap; }
1.926 albertel 4450: if ($type eq 'course') {
4451: $res='course';
4452: } elsif ($type eq 'map') {
1.588 albertel 4453: $res=&symbread($map);
4454: } else {
4455: $res=$symb;
4456: }
1.1153 www 4457: &load_all_first_access($uname,$udom);
4458: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4459: }
4460:
4461: sub set_first_access {
1.1162 raeburn 4462: my ($type,$interval)=@_;
1.790 albertel 4463: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4464: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4465: if ($type eq 'course') {
4466: $res='course';
4467: } elsif ($type eq 'map') {
1.588 albertel 4468: $res=&symbread($map);
4469: } else {
4470: $res=$symb;
4471: }
1.1153 www 4472: $cachedkey='';
1.1162 raeburn 4473: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4474: if (!$firstaccess) {
1.1162 raeburn 4475: my $start = time;
4476: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4477: $udom,$uname);
4478: if ($putres eq 'ok') {
4479: &put('timerinterval',{"$courseid\0$res"=>$interval},
4480: $udom,$uname);
4481: &appenv(
4482: {
4483: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4484: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4485: }
4486: );
4487: }
4488: return $putres;
1.505 albertel 4489: }
4490: return 'already_set';
1.504 albertel 4491: }
1.1153 www 4492: }
1.1172.2.32 raeburn 4493:
4494: sub checkout {
4495: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4496: my $now=time;
4497: my $lonhost=$perlvar{'lonHostID'};
4498: my $infostr=&escape(
4499: 'CHECKOUTTOKEN&'.
4500: $tuname.'&'.
4501: $tudom.'&'.
4502: $tcrsid.'&'.
4503: $symb.'&'.
4504: $now.'&'.$ENV{'REMOTE_ADDR'});
4505: my $token=&reply('tmpput:'.$infostr,$lonhost);
4506: if ($token=~/^error\:/) {
4507: &logthis("<font color=\"blue\">WARNING: ".
4508: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4509: "</font>");
4510: return '';
4511: }
4512:
4513: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4514: $token=~tr/a-z/A-Z/;
4515:
4516: my %infohash=('resource.0.outtoken' => $token,
4517: 'resource.0.checkouttime' => $now,
4518: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4519:
4520: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4521: return '';
4522: } else {
4523: &logthis("<font color=\"blue\">WARNING: ".
4524: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4525: "</font>");
4526: }
4527:
4528: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4529: &escape('Checkout '.$infostr.' - '.
4530: $token)) ne 'ok') {
4531: return '';
4532: } else {
4533: &logthis("<font color=\"blue\">WARNING: ".
4534: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4535: "</font>");
4536: }
4537: return $token;
4538: }
4539:
4540: # ------------------------------------------------------------ Check in an item
4541:
4542: sub checkin {
4543: my $token=shift;
4544: my $now=time;
4545: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4546: $lonhost=~tr/A-Z/a-z/;
4547: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4548: $dtoken=~s/\W/\_/g;
4549: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4550: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4551:
4552: unless (($tuname) && ($tudom)) {
4553: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4554: return '';
4555: }
4556:
4557: unless (&allowed('mgr',$tcrsid)) {
4558: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4559: $env{'user.name'}.' - '.$env{'user.domain'});
4560: return '';
4561: }
4562:
4563: my %infohash=('resource.0.intoken' => $token,
4564: 'resource.0.checkintime' => $now,
4565: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4566:
4567: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4568: return '';
4569: }
4570:
4571: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4572: &escape('Checkin - '.$token)) ne 'ok') {
4573: return '';
4574: }
4575:
4576: return ($symb,$tuname,$tudom,$tcrsid);
4577: }
4578:
1.110 www 4579: # --------------------------------------------- Set Expire Date for Spreadsheet
4580:
4581: sub expirespread {
4582: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4583: my $cid=$env{'request.course.id'};
1.110 www 4584: if ($cid) {
4585: my $now=time;
4586: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4587: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4588: $env{'course.'.$cid.'.num'}.
1.110 www 4589: ':nohist_expirationdates:'.
4590: &escape($key).'='.$now,
1.620 albertel 4591: $env{'course.'.$cid.'.home'})
1.110 www 4592: }
4593: return 'ok';
1.14 www 4594: }
4595:
1.109 www 4596: # ----------------------------------------------------- Devalidate Spreadsheets
4597:
4598: sub devalidate {
1.325 www 4599: my ($symb,$uname,$udom)=@_;
1.620 albertel 4600: my $cid=$env{'request.course.id'};
1.109 www 4601: if ($cid) {
1.391 matthew 4602: # delete the stored spreadsheets for
4603: # - the student level sheet of this user in course's homespace
4604: # - the assessment level sheet for this resource
4605: # for this user in user's homespace
1.553 albertel 4606: # - current conditional state info
1.325 www 4607: my $key=$uname.':'.$udom.':';
1.109 www 4608: my $status=
1.299 matthew 4609: &del('nohist_calculatedsheets',
1.391 matthew 4610: [$key.'studentcalc:'],
1.620 albertel 4611: $env{'course.'.$cid.'.domain'},
4612: $env{'course.'.$cid.'.num'})
1.133 albertel 4613: .' '.
4614: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4615: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4616: unless ($status eq 'ok ok') {
4617: &logthis('Could not devalidate spreadsheet '.
1.325 www 4618: $uname.' at '.$udom.' for '.
1.109 www 4619: $symb.': '.$status);
1.133 albertel 4620: }
1.553 albertel 4621: &delenv('user.state.'.$cid);
1.109 www 4622: }
4623: }
4624:
1.265 albertel 4625: sub get_scalar {
4626: my ($string,$end) = @_;
4627: my $value;
4628: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4629: $value = $1;
4630: } elsif ($$string =~ s/^([^&]*?)&//) {
4631: $value = $1;
4632: }
4633: return &unescape($value);
4634: }
4635:
4636: sub array2str {
4637: my (@array) = @_;
4638: my $result=&arrayref2str(\@array);
4639: $result=~s/^__ARRAY_REF__//;
4640: $result=~s/__END_ARRAY_REF__$//;
4641: return $result;
4642: }
4643:
1.204 albertel 4644: sub arrayref2str {
4645: my ($arrayref) = @_;
1.265 albertel 4646: my $result='__ARRAY_REF__';
1.204 albertel 4647: foreach my $elem (@$arrayref) {
1.265 albertel 4648: if(ref($elem) eq 'ARRAY') {
4649: $result.=&arrayref2str($elem).'&';
4650: } elsif(ref($elem) eq 'HASH') {
4651: $result.=&hashref2str($elem).'&';
4652: } elsif(ref($elem)) {
4653: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4654: } else {
4655: $result.=&escape($elem).'&';
4656: }
4657: }
4658: $result=~s/\&$//;
1.265 albertel 4659: $result .= '__END_ARRAY_REF__';
1.204 albertel 4660: return $result;
4661: }
4662:
1.168 albertel 4663: sub hash2str {
1.204 albertel 4664: my (%hash) = @_;
4665: my $result=&hashref2str(\%hash);
1.265 albertel 4666: $result=~s/^__HASH_REF__//;
4667: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4668: return $result;
4669: }
4670:
4671: sub hashref2str {
4672: my ($hashref)=@_;
1.265 albertel 4673: my $result='__HASH_REF__';
1.800 albertel 4674: foreach my $key (sort(keys(%$hashref))) {
4675: if (ref($key) eq 'ARRAY') {
4676: $result.=&arrayref2str($key).'=';
4677: } elsif (ref($key) eq 'HASH') {
4678: $result.=&hashref2str($key).'=';
4679: } elsif (ref($key)) {
1.265 albertel 4680: $result.='=';
1.800 albertel 4681: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4682: } else {
1.1132 raeburn 4683: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4684: }
4685:
1.800 albertel 4686: if(ref($hashref->{$key}) eq 'ARRAY') {
4687: $result.=&arrayref2str($hashref->{$key}).'&';
4688: } elsif(ref($hashref->{$key}) eq 'HASH') {
4689: $result.=&hashref2str($hashref->{$key}).'&';
4690: } elsif(ref($hashref->{$key})) {
1.265 albertel 4691: $result.='&';
1.800 albertel 4692: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4693: } else {
1.800 albertel 4694: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4695: }
4696: }
1.168 albertel 4697: $result=~s/\&$//;
1.265 albertel 4698: $result .= '__END_HASH_REF__';
1.168 albertel 4699: return $result;
4700: }
4701:
4702: sub str2hash {
1.265 albertel 4703: my ($string)=@_;
4704: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4705: return %$hash;
4706: }
4707:
4708: sub str2hashref {
1.168 albertel 4709: my ($string) = @_;
1.265 albertel 4710:
4711: my %hash;
4712:
4713: if($string !~ /^__HASH_REF__/) {
4714: if (! ($string eq '' || !defined($string))) {
4715: $hash{'error'}='Not hash reference';
4716: }
4717: return (\%hash, $string);
4718: }
4719:
4720: $string =~ s/^__HASH_REF__//;
4721:
4722: while($string !~ /^__END_HASH_REF__/) {
4723: #key
4724: my $key='';
4725: if($string =~ /^__HASH_REF__/) {
4726: ($key, $string)=&str2hashref($string);
4727: if(defined($key->{'error'})) {
4728: $hash{'error'}='Bad data';
4729: return (\%hash, $string);
4730: }
4731: } elsif($string =~ /^__ARRAY_REF__/) {
4732: ($key, $string)=&str2arrayref($string);
4733: if($key->[0] eq 'Array reference error') {
4734: $hash{'error'}='Bad data';
4735: return (\%hash, $string);
4736: }
4737: } else {
4738: $string =~ s/^(.*?)=//;
1.267 albertel 4739: $key=&unescape($1);
1.265 albertel 4740: }
4741: $string =~ s/^=//;
4742:
4743: #value
4744: my $value='';
4745: if($string =~ /^__HASH_REF__/) {
4746: ($value, $string)=&str2hashref($string);
4747: if(defined($value->{'error'})) {
4748: $hash{'error'}='Bad data';
4749: return (\%hash, $string);
4750: }
4751: } elsif($string =~ /^__ARRAY_REF__/) {
4752: ($value, $string)=&str2arrayref($string);
4753: if($value->[0] eq 'Array reference error') {
4754: $hash{'error'}='Bad data';
4755: return (\%hash, $string);
4756: }
4757: } else {
4758: $value=&get_scalar(\$string,'__END_HASH_REF__');
4759: }
4760: $string =~ s/^&//;
4761:
4762: $hash{$key}=$value;
1.204 albertel 4763: }
1.265 albertel 4764:
4765: $string =~ s/^__END_HASH_REF__//;
4766:
4767: return (\%hash, $string);
1.204 albertel 4768: }
4769:
4770: sub str2array {
1.265 albertel 4771: my ($string)=@_;
4772: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4773: return @$array;
4774: }
4775:
4776: sub str2arrayref {
1.204 albertel 4777: my ($string) = @_;
1.265 albertel 4778: my @array;
4779:
4780: if($string !~ /^__ARRAY_REF__/) {
4781: if (! ($string eq '' || !defined($string))) {
4782: $array[0]='Array reference error';
4783: }
4784: return (\@array, $string);
4785: }
4786:
4787: $string =~ s/^__ARRAY_REF__//;
4788:
4789: while($string !~ /^__END_ARRAY_REF__/) {
4790: my $value='';
4791: if($string =~ /^__HASH_REF__/) {
4792: ($value, $string)=&str2hashref($string);
4793: if(defined($value->{'error'})) {
4794: $array[0] ='Array reference error';
4795: return (\@array, $string);
4796: }
4797: } elsif($string =~ /^__ARRAY_REF__/) {
4798: ($value, $string)=&str2arrayref($string);
4799: if($value->[0] eq 'Array reference error') {
4800: $array[0] ='Array reference error';
4801: return (\@array, $string);
4802: }
4803: } else {
4804: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4805: }
4806: $string =~ s/^&//;
4807:
4808: push(@array, $value);
1.191 harris41 4809: }
1.265 albertel 4810:
4811: $string =~ s/^__END_ARRAY_REF__//;
4812:
4813: return (\@array, $string);
1.168 albertel 4814: }
4815:
1.167 albertel 4816: # -------------------------------------------------------------------Temp Store
4817:
1.168 albertel 4818: sub tmpreset {
4819: my ($symb,$namespace,$domain,$stuname) = @_;
4820: if (!$symb) {
4821: $symb=&symbread();
1.620 albertel 4822: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4823: }
4824: $symb=escape($symb);
4825:
1.620 albertel 4826: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4827: $namespace=~s/\//\_/g;
4828: $namespace=~s/\W//g;
4829:
1.620 albertel 4830: if (!$domain) { $domain=$env{'user.domain'}; }
4831: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4832: if ($domain eq 'public' && $stuname eq 'public') {
4833: $stuname=$ENV{'REMOTE_ADDR'};
4834: }
1.1117 foxr 4835: my $path=LONCAPA::tempdir();
1.168 albertel 4836: my %hash;
4837: if (tie(%hash,'GDBM_File',
4838: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4839: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4840: foreach my $key (keys(%hash)) {
1.180 albertel 4841: if ($key=~ /:$symb/) {
1.168 albertel 4842: delete($hash{$key});
4843: }
4844: }
4845: }
4846: }
4847:
1.167 albertel 4848: sub tmpstore {
1.168 albertel 4849: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4850:
4851: if (!$symb) {
4852: $symb=&symbread();
1.620 albertel 4853: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4854: }
4855: $symb=escape($symb);
4856:
4857: if (!$namespace) {
4858: # I don't think we would ever want to store this for a course.
4859: # it seems this will only be used if we don't have a course.
1.620 albertel 4860: #$namespace=$env{'request.course.id'};
1.168 albertel 4861: #if (!$namespace) {
1.620 albertel 4862: $namespace=$env{'request.state'};
1.168 albertel 4863: #}
4864: }
4865: $namespace=~s/\//\_/g;
4866: $namespace=~s/\W//g;
1.620 albertel 4867: if (!$domain) { $domain=$env{'user.domain'}; }
4868: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4869: if ($domain eq 'public' && $stuname eq 'public') {
4870: $stuname=$ENV{'REMOTE_ADDR'};
4871: }
1.168 albertel 4872: my $now=time;
4873: my %hash;
1.1117 foxr 4874: my $path=LONCAPA::tempdir();
1.168 albertel 4875: if (tie(%hash,'GDBM_File',
4876: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4877: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4878: $hash{"version:$symb"}++;
4879: my $version=$hash{"version:$symb"};
4880: my $allkeys='';
4881: foreach my $key (keys(%$storehash)) {
4882: $allkeys.=$key.':';
1.591 albertel 4883: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4884: }
4885: $hash{"$version:$symb:timestamp"}=$now;
4886: $allkeys.='timestamp';
4887: $hash{"$version:keys:$symb"}=$allkeys;
4888: if (untie(%hash)) {
4889: return 'ok';
4890: } else {
4891: return "error:$!";
4892: }
4893: } else {
4894: return "error:$!";
4895: }
4896: }
1.167 albertel 4897:
1.168 albertel 4898: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4899:
1.168 albertel 4900: sub tmprestore {
4901: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4902:
1.168 albertel 4903: if (!$symb) {
4904: $symb=&symbread();
1.620 albertel 4905: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4906: }
4907: $symb=escape($symb);
4908:
1.620 albertel 4909: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4910:
1.620 albertel 4911: if (!$domain) { $domain=$env{'user.domain'}; }
4912: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4913: if ($domain eq 'public' && $stuname eq 'public') {
4914: $stuname=$ENV{'REMOTE_ADDR'};
4915: }
1.168 albertel 4916: my %returnhash;
4917: $namespace=~s/\//\_/g;
4918: $namespace=~s/\W//g;
4919: my %hash;
1.1117 foxr 4920: my $path=LONCAPA::tempdir();
1.168 albertel 4921: if (tie(%hash,'GDBM_File',
4922: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4923: &GDBM_READER(),0640)) {
1.168 albertel 4924: my $version=$hash{"version:$symb"};
4925: $returnhash{'version'}=$version;
4926: my $scope;
4927: for ($scope=1;$scope<=$version;$scope++) {
4928: my $vkeys=$hash{"$scope:keys:$symb"};
4929: my @keys=split(/:/,$vkeys);
4930: my $key;
4931: $returnhash{"$scope:keys"}=$vkeys;
4932: foreach $key (@keys) {
1.591 albertel 4933: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4934: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4935: }
4936: }
1.168 albertel 4937: if (!(untie(%hash))) {
4938: return "error:$!";
4939: }
4940: } else {
4941: return "error:$!";
4942: }
4943: return %returnhash;
1.167 albertel 4944: }
4945:
1.9 www 4946: # ----------------------------------------------------------------------- Store
4947:
4948: sub store {
1.124 www 4949: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4950: my $home='';
4951:
1.168 albertel 4952: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4953:
1.213 www 4954: $symb=&symbclean($symb);
1.122 albertel 4955: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4956:
1.620 albertel 4957: if (!$domain) { $domain=$env{'user.domain'}; }
4958: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4959:
4960: &devalidate($symb,$stuname,$domain);
1.109 www 4961:
4962: $symb=escape($symb);
1.187 www 4963: if (!$namespace) {
1.620 albertel 4964: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4965: return '';
4966: }
4967: }
1.620 albertel 4968: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4969:
4970: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4971: $$storehash{'host'}=$perlvar{'lonHostID'};
4972:
1.12 www 4973: my $namevalue='';
1.800 albertel 4974: foreach my $key (keys(%$storehash)) {
4975: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4976: }
1.12 www 4977: $namevalue=~s/\&$//;
1.187 www 4978: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4979: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4980: }
4981:
1.47 www 4982: # -------------------------------------------------------------- Critical Store
4983:
4984: sub cstore {
1.124 www 4985: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4986: my $home='';
4987:
1.168 albertel 4988: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4989:
1.213 www 4990: $symb=&symbclean($symb);
1.122 albertel 4991: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4992:
1.620 albertel 4993: if (!$domain) { $domain=$env{'user.domain'}; }
4994: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4995:
4996: &devalidate($symb,$stuname,$domain);
1.109 www 4997:
4998: $symb=escape($symb);
1.187 www 4999: if (!$namespace) {
1.620 albertel 5000: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5001: return '';
5002: }
5003: }
1.620 albertel 5004: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5005:
5006: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5007: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5008:
1.47 www 5009: my $namevalue='';
1.800 albertel 5010: foreach my $key (keys(%$storehash)) {
5011: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5012: }
1.47 www 5013: $namevalue=~s/\&$//;
1.187 www 5014: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5015: return critical
5016: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 5017: }
5018:
1.9 www 5019: # --------------------------------------------------------------------- Restore
5020:
5021: sub restore {
1.124 www 5022: my ($symb,$namespace,$domain,$stuname) = @_;
5023: my $home='';
5024:
1.168 albertel 5025: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5026:
1.122 albertel 5027: if (!$symb) {
1.1172.2.26 raeburn 5028: return if ($namespace eq 'courserequests');
5029: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5030: } else {
1.1172.2.26 raeburn 5031: unless ($namespace eq 'courserequests') {
5032: $symb=&escape(&symbclean($symb));
5033: }
1.122 albertel 5034: }
1.188 www 5035: if (!$namespace) {
1.620 albertel 5036: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5037: return '';
5038: }
5039: }
1.620 albertel 5040: if (!$domain) { $domain=$env{'user.domain'}; }
5041: if (!$stuname) { $stuname=$env{'user.name'}; }
5042: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5043: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5044:
1.12 www 5045: my %returnhash=();
1.800 albertel 5046: foreach my $line (split(/\&/,$answer)) {
5047: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5048: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5049: }
1.75 www 5050: my $version;
5051: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5052: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5053: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5054: }
1.75 www 5055: }
1.13 www 5056: return %returnhash;
1.34 www 5057: }
5058:
5059: # ---------------------------------------------------------- Course Description
1.1118 foxr 5060: #
5061: #
1.34 www 5062:
5063: sub coursedescription {
1.731 albertel 5064: my ($courseid,$args)=@_;
1.34 www 5065: $courseid=~s/^\///;
1.49 www 5066: $courseid=~s/\_/\//g;
1.34 www 5067: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5068: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5069: my $normalid=$cdomain.'_'.$cnum;
5070: # need to always cache even if we get errors otherwise we keep
5071: # trying and trying and trying to get the course description.
5072: my %envhash=();
5073: my %returnhash=();
1.731 albertel 5074:
5075: my $expiretime=600;
5076: if ($env{'request.course.id'} eq $normalid) {
5077: $expiretime=120;
5078: }
5079:
5080: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5081: if (!$args->{'freshen_cache'}
5082: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5083: foreach my $key (keys(%env)) {
5084: next if ($key !~ /^\Q$prefix\E(.*)/);
5085: my ($setting) = $1;
5086: $returnhash{$setting} = $env{$key};
5087: }
5088: return %returnhash;
5089: }
5090:
1.1118 foxr 5091: # get the data again
5092:
1.731 albertel 5093: if (!$args->{'one_time'}) {
5094: $envhash{'course.'.$normalid.'.last_cache'}=time;
5095: }
1.811 albertel 5096:
1.34 www 5097: if ($chome ne 'no_host') {
1.302 albertel 5098: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5099: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5100: my $username = $env{'user.name'}; # Defult username
5101: if(defined $args->{'user'}) {
5102: $username = $args->{'user'};
5103: }
1.129 albertel 5104: $returnhash{'home'}= $chome;
5105: $returnhash{'domain'} = $cdomain;
5106: $returnhash{'num'} = $cnum;
1.741 raeburn 5107: if (!defined($returnhash{'type'})) {
5108: $returnhash{'type'} = 'Course';
5109: }
1.130 albertel 5110: while (my ($name,$value) = each %returnhash) {
1.53 www 5111: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5112: }
1.270 www 5113: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5114: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5115: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5116: $envhash{'course.'.$normalid.'.home'}=$chome;
5117: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5118: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5119: }
5120: }
1.731 albertel 5121: if (!$args->{'one_time'}) {
1.949 raeburn 5122: &appenv(\%envhash);
1.731 albertel 5123: }
1.302 albertel 5124: return %returnhash;
1.461 www 5125: }
5126:
1.1080 raeburn 5127: sub update_released_required {
5128: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5129: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5130: $cid = $env{'request.course.id'};
5131: $cdom = $env{'course.'.$cid.'.domain'};
5132: $cnum = $env{'course.'.$cid.'.num'};
5133: $chome = $env{'course.'.$cid.'.home'};
5134: }
5135: if ($needsrelease) {
5136: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5137: my $needsupdate;
5138: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5139: $needsupdate = 1;
5140: } else {
5141: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5142: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5143: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5144: $needsupdate = 1;
5145: }
5146: }
5147: if ($needsupdate) {
5148: my %needshash = (
5149: 'internal.releaserequired' => $needsrelease,
5150: );
5151: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5152: if ($putresult eq 'ok') {
5153: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5154: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5155: if (ref($crsinfo{$cid}) eq 'HASH') {
5156: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5157: &courseidput($cdom,\%crsinfo,$chome,'notime');
5158: }
5159: }
5160: }
5161: }
5162: return;
5163: }
5164:
1.461 www 5165: # -------------------------------------------------See if a user is privileged
5166:
5167: sub privileged {
1.1172.2.23 raeburn 5168: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5169: my $now = time;
1.1172.2.23 raeburn 5170: my $roles;
5171: if (ref($possroles) eq 'ARRAY') {
5172: $roles = $possroles;
5173: } else {
5174: $roles = ['dc','su'];
5175: }
5176: if (ref($possdomains) eq 'ARRAY') {
5177: my %privileged = &privileged_by_domain($possdomains,$roles);
5178: foreach my $dom (@{$possdomains}) {
5179: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5180: (ref($privileged{$dom}) eq 'HASH')) {
5181: foreach my $role (@{$roles}) {
5182: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5183: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5184: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5185: return 1 unless (($end && $end < $now) ||
5186: ($start && $start > $now));
5187: }
5188: }
5189: }
5190: }
5191: }
5192: } else {
5193: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5194: my $now = time;
1.1170 droeschl 5195:
1.1172.2.58 raeburn 5196: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5197: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5198: if (grep(/^\Q$trole\E$/,@{$roles})) {
5199: return 1 unless ($tend && $tend < $now)
5200: or ($tstart && $tstart > $now);
1.1170 droeschl 5201: }
1.1172.2.23 raeburn 5202: }
5203: }
1.461 www 5204: return 0;
1.9 www 5205: }
1.1 albertel 5206:
1.1172.2.23 raeburn 5207: sub privileged_by_domain {
5208: my ($domains,$roles) = @_;
5209: my %privileged = ();
5210: my $cachetime = 60*60*24;
5211: my $now = time;
5212: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5213: return %privileged;
5214: }
5215: foreach my $dom (@{$domains}) {
5216: next if (ref($privileged{$dom}) eq 'HASH');
5217: my $needroles;
5218: foreach my $role (@{$roles}) {
5219: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5220: if (defined($cached)) {
5221: if (ref($result) eq 'HASH') {
5222: $privileged{$dom}{$role} = $result;
5223: }
5224: } else {
5225: $needroles = 1;
5226: }
5227: }
5228: if ($needroles) {
5229: my %dompersonnel = &get_domain_roles($dom,$roles);
5230: $privileged{$dom} = {};
5231: foreach my $server (keys(%dompersonnel)) {
5232: if (ref($dompersonnel{$server}) eq 'HASH') {
5233: foreach my $item (keys(%{$dompersonnel{$server}})) {
5234: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5235: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5236: next if ($end && $end < $now);
5237: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5238: $dompersonnel{$server}{$item};
5239: }
5240: }
5241: }
5242: if (ref($privileged{$dom}) eq 'HASH') {
5243: foreach my $role (@{$roles}) {
5244: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5245: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5246: } else {
5247: my %hash = ();
5248: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5249: }
5250: }
5251: }
5252: }
5253: }
5254: return %privileged;
5255: }
5256:
1.103 harris41 5257: # -------------------------------------------------------- Get user privileges
1.11 www 5258:
5259: sub rolesinit {
1.1169 droeschl 5260: my ($domain, $username) = @_;
5261: my %userroles = ('user.login.time' => time);
5262: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5263:
5264: # firstaccess and timerinterval are related to timed maps/resources.
5265: # also, blocking can be triggered by an activating timer
5266: # it's saved in the user's %env.
5267: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5268: my %timerinterval = &dump('timerinterval', $domain, $username);
5269: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5270: %timerintchk, %timerintenv);
5271:
1.1162 raeburn 5272: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5273: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5274: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5275: }
1.1169 droeschl 5276:
1.1162 raeburn 5277: foreach my $key (keys(%timerinterval)) {
5278: my ($cid,$rest) = split(/\0/,$key);
5279: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5280: }
1.1169 droeschl 5281:
1.11 www 5282: my %allroles=();
1.1162 raeburn 5283: my %allgroups=();
1.11 www 5284:
1.1172.2.58 raeburn 5285: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5286: my $role = $rolesdump{$area};
5287: $area =~ s/\_\w\w$//;
5288:
5289: my ($trole, $tend, $tstart, $group_privs);
5290:
5291: if ($role =~ /^cr/) {
5292: # Custom role, defined by a user
5293: # e.g., user.role.cr/msu/smith/mynewrole
5294: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5295: $trole = $1;
5296: ($tend, $tstart) = split('_', $2);
5297: } else {
5298: $trole = $role;
5299: }
5300: } elsif ($role =~ m|^gr/|) {
5301: # Role of member in a group, defined within a course/community
5302: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5303: ($trole, $tend, $tstart) = split(/_/, $role);
5304: next if $tstart eq '-1';
5305: ($trole, $group_privs) = split(/\//, $trole);
5306: $group_privs = &unescape($group_privs);
5307: } else {
5308: # Just a normal role, defined in roles.tab
5309: ($trole, $tend, $tstart) = split(/_/,$role);
5310: }
5311:
5312: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5313: $username);
5314: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5315:
5316: # role expired or not available yet?
5317: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5318: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5319:
5320: next if $area eq '' or $trole eq '';
5321:
5322: my $spec = "$trole.$area";
5323: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5324:
5325: if ($trole =~ /^cr\//) {
5326: # Custom role, defined by a user
5327: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5328: } elsif ($trole eq 'gr') {
5329: # Role of a member in a group, defined within a course/community
5330: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5331: next;
5332: } else {
5333: # Normal role, defined in roles.tab
5334: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5335: }
5336:
5337: my $cid = $tdomain.'_'.$trest;
5338: unless ($firstaccchk{$cid}) {
5339: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5340: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5341: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5342: $coursetimerstarts{$cid}{$item};
5343: }
5344: }
5345: $firstaccchk{$cid} = 1;
5346: }
5347: unless ($timerintchk{$cid}) {
5348: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5349: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5350: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5351: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5352: }
1.12 www 5353: }
1.1169 droeschl 5354: $timerintchk{$cid} = 1;
1.191 harris41 5355: }
1.11 www 5356: }
1.1169 droeschl 5357:
5358: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5359: \%allroles, \%allgroups);
5360: $env{'user.adv'} = $userroles{'user.adv'};
5361:
1.1162 raeburn 5362: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5363: }
5364:
1.567 raeburn 5365: sub set_arearole {
1.1172.2.19 raeburn 5366: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5367: unless ($nolog) {
1.567 raeburn 5368: # log the associated role with the area
1.1172.2.19 raeburn 5369: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5370: }
1.743 albertel 5371: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5372: }
5373:
5374: sub custom_roleprivs {
5375: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5376: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5377: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5378: if (&hostname($homsvr) ne '') {
1.567 raeburn 5379: my ($rdummy,$roledef)=
5380: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5381: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5382: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5383: if (defined($syspriv)) {
1.1043 raeburn 5384: if ($trest =~ /^$match_community$/) {
5385: $syspriv =~ s/bre\&S//;
5386: }
1.567 raeburn 5387: $$allroles{'cm./'}.=':'.$syspriv;
5388: $$allroles{$spec.'./'}.=':'.$syspriv;
5389: }
5390: if ($tdomain ne '') {
5391: if (defined($dompriv)) {
5392: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5393: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5394: }
5395: if (($trest ne '') && (defined($coursepriv))) {
5396: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5397: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5398: }
5399: }
5400: }
5401: }
5402: }
5403:
1.678 raeburn 5404: sub group_roleprivs {
5405: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5406: my $access = 1;
5407: my $now = time;
5408: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5409: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5410: if ($access) {
1.811 albertel 5411: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5412: $$allgroups{$course}{$group} .=':'.$group_privs;
5413: }
5414: }
1.567 raeburn 5415:
5416: sub standard_roleprivs {
5417: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5418: if (defined($pr{$trole.':s'})) {
5419: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5420: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5421: }
5422: if ($tdomain ne '') {
5423: if (defined($pr{$trole.':d'})) {
5424: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5425: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5426: }
5427: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5428: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5429: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5430: }
5431: }
5432: }
5433:
5434: sub set_userprivs {
1.1064 raeburn 5435: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5436: my $author=0;
5437: my $adv=0;
1.678 raeburn 5438: my %grouproles = ();
5439: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5440: my @groupkeys;
1.1000 raeburn 5441: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5442: push(@groupkeys,$role);
5443: }
5444: if (ref($groups_roles) eq 'HASH') {
5445: foreach my $key (keys(%{$groups_roles})) {
5446: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5447: push(@groupkeys,$key);
5448: }
5449: }
5450: }
5451: if (@groupkeys > 0) {
5452: foreach my $role (@groupkeys) {
5453: my ($trole,$area,$sec,$extendedarea);
5454: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5455: $trole = $1;
5456: $area = $2;
5457: $sec = $3;
5458: $extendedarea = $area.$sec;
5459: if (exists($$allgroups{$area})) {
5460: foreach my $group (keys(%{$$allgroups{$area}})) {
5461: my $spec = $trole.'.'.$extendedarea;
5462: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5463: $$allgroups{$area}{$group};
1.1064 raeburn 5464: }
1.678 raeburn 5465: }
5466: }
5467: }
5468: }
5469: }
1.800 albertel 5470: foreach my $group (keys(%grouproles)) {
5471: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5472: }
1.800 albertel 5473: foreach my $role (keys(%{$allroles})) {
5474: my %thesepriv;
1.941 raeburn 5475: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5476: foreach my $item (split(/:/,$$allroles{$role})) {
5477: if ($item ne '') {
5478: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5479: if ($restrictions eq '') {
5480: $thesepriv{$privilege}='F';
5481: } elsif ($thesepriv{$privilege} ne 'F') {
5482: $thesepriv{$privilege}.=$restrictions;
5483: }
5484: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5485: }
5486: }
5487: my $thesestr='';
1.1104 raeburn 5488: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5489: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5490: }
5491: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5492: }
5493: return ($author,$adv);
5494: }
5495:
1.994 raeburn 5496: sub role_status {
1.1104 raeburn 5497: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5498: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5499: my ($one,$two) = split(m{\./},$rolekey,2);
5500: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5501: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5502: $$where = '/'.$two;
1.994 raeburn 5503: $$trolecode=$$role.'.'.$$where;
5504: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5505: $$tstatus='is';
1.1104 raeburn 5506: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5507: $$tstatus='future';
1.1034 raeburn 5508: if ($$tstart<$now) {
5509: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5510: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5511: my (%allroles,%allgroups,$group_privs,
5512: %groups_roles,@rolecodes);
1.1002 raeburn 5513: my %userroles = (
5514: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5515: );
1.1064 raeburn 5516: @rolecodes = ('cm');
1.1002 raeburn 5517: my $spec=$$role.'.'.$$where;
5518: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5519: if ($$role =~ /^cr\//) {
5520: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5521: push(@rolecodes,'cr');
1.1002 raeburn 5522: } elsif ($$role eq 'gr') {
1.1064 raeburn 5523: push(@rolecodes,$$role);
1.1002 raeburn 5524: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5525: $env{'user.name'});
1.1064 raeburn 5526: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5527: (undef,my $group_privs) = split(/\//,$trole);
5528: $group_privs = &unescape($group_privs);
5529: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5530: 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 5531: &get_groups_roles($tdomain,$trest,
5532: \%course_roles,\@rolecodes,
5533: \%groups_roles);
1.1002 raeburn 5534: } else {
1.1064 raeburn 5535: push(@rolecodes,$$role);
1.1002 raeburn 5536: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5537: }
1.1064 raeburn 5538: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5539: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5540: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5541: }
5542: }
1.1034 raeburn 5543: $$tstatus = 'is';
1.1002 raeburn 5544: }
1.994 raeburn 5545: }
5546: if ($$tend) {
1.1104 raeburn 5547: if ($$tend<$update) {
1.994 raeburn 5548: $$tstatus='expired';
5549: } elsif ($$tend<$now) {
5550: $$tstatus='will_not';
5551: }
5552: }
5553: }
5554: }
5555: }
5556:
1.1104 raeburn 5557: sub get_groups_roles {
5558: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5559: return unless((ref($cdom_courseroles) eq 'HASH') &&
5560: (ref($rolecodes) eq 'ARRAY') &&
5561: (ref($groups_roles) eq 'HASH'));
5562: if (keys(%{$cdom_courseroles}) > 0) {
5563: my ($cnum) = ($rest =~ /^($match_courseid)/);
5564: if ($cdom ne '' && $cnum ne '') {
5565: foreach my $key (keys(%{$cdom_courseroles})) {
5566: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5567: my $crsrole = $1;
5568: my $crssec = $2;
5569: if ($crsrole =~ /^cr/) {
5570: unless (grep(/^cr$/,@{$rolecodes})) {
5571: push(@{$rolecodes},'cr');
5572: }
5573: } else {
5574: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5575: push(@{$rolecodes},$crsrole);
5576: }
5577: }
5578: my $rolekey = "$crsrole./$cdom/$cnum";
5579: if ($crssec ne '') {
5580: $rolekey .= "/$crssec";
5581: }
5582: $rolekey .= './';
5583: $groups_roles->{$rolekey} = $rolecodes;
5584: }
5585: }
5586: }
5587: }
5588: return;
5589: }
5590:
5591: sub delete_env_groupprivs {
5592: my ($where,$courseroles,$possroles) = @_;
5593: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5594: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5595: unless (ref($courseroles->{$udom}) eq 'HASH') {
5596: %{$courseroles->{$udom}} =
5597: &get_my_roles('','','userroles',['active'],
5598: $possroles,[$udom],1);
5599: }
5600: if (ref($courseroles->{$udom}) eq 'HASH') {
5601: foreach my $item (keys(%{$courseroles->{$udom}})) {
5602: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5603: my $area = '/'.$cdom.'/'.$cnum;
5604: my $privkey = "user.priv.$crsrole.$area";
5605: if ($crssec ne '') {
5606: $privkey .= '/'.$crssec;
5607: }
5608: $privkey .= ".$area/$group";
5609: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5610: }
5611: }
5612: return;
5613: }
5614:
1.994 raeburn 5615: sub check_adhoc_privs {
1.1104 raeburn 5616: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5617: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5618: my $setprivs;
1.994 raeburn 5619: if ($env{$cckey}) {
5620: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5621: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5622: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5623: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5624: $setprivs = 1;
1.994 raeburn 5625: }
5626: } else {
1.1088 raeburn 5627: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5628: $setprivs = 1;
1.994 raeburn 5629: }
1.1172.2.9 raeburn 5630: return $setprivs;
1.994 raeburn 5631: }
5632:
5633: sub set_adhoc_privileges {
5634: # role can be cc or ca
1.1088 raeburn 5635: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5636: my $area = '/'.$dcdom.'/'.$pickedcourse;
5637: my $spec = $role.'.'.$area;
5638: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5639: $env{'user.name'},1);
1.994 raeburn 5640: my %ccrole = ();
5641: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5642: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5643: &appenv(\%userroles,[$role,'cm']);
5644: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5645: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5646: &appenv( {'request.role' => $spec,
5647: 'request.role.domain' => $dcdom,
5648: 'request.course.sec' => ''
5649: }
5650: );
5651: my $tadv=0;
5652: if (&allowed('adv') eq 'F') { $tadv=1; }
5653: &appenv({'request.role.adv' => $tadv});
5654: }
1.994 raeburn 5655: }
5656:
1.12 www 5657: # --------------------------------------------------------------- get interface
5658:
5659: sub get {
1.131 albertel 5660: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5661: my $items='';
1.800 albertel 5662: foreach my $item (@$storearr) {
5663: $items.=&escape($item).'&';
1.191 harris41 5664: }
1.12 www 5665: $items=~s/\&$//;
1.620 albertel 5666: if (!$udomain) { $udomain=$env{'user.domain'}; }
5667: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5668: my $uhome=&homeserver($uname,$udomain);
5669:
1.133 albertel 5670: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5671: my @pairs=split(/\&/,$rep);
1.273 albertel 5672: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5673: return @pairs;
5674: }
1.15 www 5675: my %returnhash=();
1.42 www 5676: my $i=0;
1.800 albertel 5677: foreach my $item (@$storearr) {
5678: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5679: $i++;
1.191 harris41 5680: }
1.15 www 5681: return %returnhash;
1.27 www 5682: }
5683:
5684: # --------------------------------------------------------------- del interface
5685:
5686: sub del {
1.133 albertel 5687: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5688: my $items='';
1.800 albertel 5689: foreach my $item (@$storearr) {
5690: $items.=&escape($item).'&';
1.191 harris41 5691: }
1.984 neumanie 5692:
1.27 www 5693: $items=~s/\&$//;
1.620 albertel 5694: if (!$udomain) { $udomain=$env{'user.domain'}; }
5695: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5696: my $uhome=&homeserver($uname,$udomain);
5697: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5698: }
5699:
5700: # -------------------------------------------------------------- dump interface
5701:
1.1172.2.22 raeburn 5702: sub unserialize {
5703: my ($rep, $escapedkeys) = @_;
5704:
5705: return {} if $rep =~ /^error/;
5706:
5707: my %returnhash=();
5708: foreach my $item (split(/\&/,$rep)) {
5709: my ($key, $value) = split(/=/, $item, 2);
5710: $key = unescape($key) unless $escapedkeys;
5711: next if $key =~ /^error: 2 /;
5712: $returnhash{$key} = &thaw_unescape($value);
5713: }
5714: return \%returnhash;
5715: }
5716:
5717: # see Lond::dump_with_regexp
5718: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5719: sub dump {
1.1172.2.22 raeburn 5720: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5721: if (!$udomain) { $udomain=$env{'user.domain'}; }
5722: if (!$uname) { $uname=$env{'user.name'}; }
5723: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5724:
1.1172.2.55 raeburn 5725: if ($regexp) {
5726: $regexp=&escape($regexp);
5727: } else {
5728: $regexp='.';
5729: }
1.1172.2.22 raeburn 5730: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5731: # user is hosted on this machine
1.1172.2.55 raeburn 5732: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5733: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5734: return %{&unserialize($reply, $escapedkeys)};
5735: }
1.1166 raeburn 5736: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5737: my @pairs=split(/\&/,$rep);
5738: my %returnhash=();
1.1098 foxr 5739: if (!($rep =~ /^error/ )) {
5740: foreach my $item (@pairs) {
5741: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5742: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5743: next if ($key =~ /^error: 2 /);
5744: $returnhash{$key}=&thaw_unescape($value);
5745: }
1.755 albertel 5746: }
5747: return %returnhash;
1.407 www 5748: }
5749:
1.1098 foxr 5750:
1.717 albertel 5751: # --------------------------------------------------------- dumpstore interface
5752:
5753: sub dumpstore {
5754: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5755: # same as dump but keys must be escaped. They may contain colon separated
5756: # lists of values that may themself contain colons (e.g. symbs).
5757: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5758: }
5759:
1.407 www 5760: # -------------------------------------------------------------- keys interface
5761:
5762: sub getkeys {
5763: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5764: if (!$udomain) { $udomain=$env{'user.domain'}; }
5765: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5766: my $uhome=&homeserver($uname,$udomain);
5767: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5768: my @keyarray=();
1.800 albertel 5769: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5770: next if ($key =~ /^error: 2 /);
1.800 albertel 5771: push(@keyarray,&unescape($key));
1.407 www 5772: }
5773: return @keyarray;
1.318 matthew 5774: }
5775:
1.319 matthew 5776: # --------------------------------------------------------------- currentdump
5777: sub currentdump {
1.328 matthew 5778: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5779: $courseid = $env{'request.course.id'} if (! defined($courseid));
5780: $sdom = $env{'user.domain'} if (! defined($sdom));
5781: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5782: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5783: my $rep;
5784:
5785: if (grep { $_ eq $uhome } current_machine_ids()) {
5786: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5787: $courseid)));
5788: } else {
5789: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5790: }
5791:
1.318 matthew 5792: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5793: #
1.318 matthew 5794: my %returnhash=();
1.319 matthew 5795: #
5796: if ($rep eq "unknown_cmd") {
5797: # an old lond will not know currentdump
5798: # Do a dump and make it look like a currentdump
1.822 albertel 5799: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5800: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5801: my %hash = @tmp;
5802: @tmp=();
1.424 matthew 5803: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5804: } else {
5805: my @pairs=split(/\&/,$rep);
1.800 albertel 5806: foreach my $pair (@pairs) {
5807: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5808: my ($symb,$param) = split(/:/,$key);
5809: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5810: &thaw_unescape($value);
1.319 matthew 5811: }
1.191 harris41 5812: }
1.12 www 5813: return %returnhash;
1.424 matthew 5814: }
5815:
5816: sub convert_dump_to_currentdump{
5817: my %hash = %{shift()};
5818: my %returnhash;
5819: # Code ripped from lond, essentially. The only difference
5820: # here is the unescaping done by lonnet::dump(). Conceivably
5821: # we might run in to problems with parameter names =~ /^v\./
5822: while (my ($key,$value) = each(%hash)) {
5823: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5824: $symb = &unescape($symb);
5825: $param = &unescape($param);
1.424 matthew 5826: next if ($v eq 'version' || $symb eq 'keys');
5827: next if (exists($returnhash{$symb}) &&
5828: exists($returnhash{$symb}->{$param}) &&
5829: $returnhash{$symb}->{'v.'.$param} > $v);
5830: $returnhash{$symb}->{$param}=$value;
5831: $returnhash{$symb}->{'v.'.$param}=$v;
5832: }
5833: #
5834: # Remove all of the keys in the hashes which keep track of
5835: # the version of the parameter.
5836: while (my ($symb,$param_hash) = each(%returnhash)) {
5837: # use a foreach because we are going to delete from the hash.
5838: foreach my $key (keys(%$param_hash)) {
5839: delete($param_hash->{$key}) if ($key =~ /^v\./);
5840: }
5841: }
5842: return \%returnhash;
1.12 www 5843: }
5844:
1.627 albertel 5845: # ------------------------------------------------------ critical inc interface
5846:
5847: sub cinc {
5848: return &inc(@_,'critical');
5849: }
5850:
1.449 matthew 5851: # --------------------------------------------------------------- inc interface
5852:
5853: sub inc {
1.627 albertel 5854: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5855: if (!$udomain) { $udomain=$env{'user.domain'}; }
5856: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5857: my $uhome=&homeserver($uname,$udomain);
5858: my $items='';
5859: if (! ref($store)) {
5860: # got a single value, so use that instead
5861: $items = &escape($store).'=&';
5862: } elsif (ref($store) eq 'SCALAR') {
5863: $items = &escape($$store).'=&';
5864: } elsif (ref($store) eq 'ARRAY') {
5865: $items = join('=&',map {&escape($_);} @{$store});
5866: } elsif (ref($store) eq 'HASH') {
5867: while (my($key,$value) = each(%{$store})) {
5868: $items.= &escape($key).'='.&escape($value).'&';
5869: }
5870: }
5871: $items=~s/\&$//;
1.627 albertel 5872: if ($critical) {
5873: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5874: } else {
5875: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5876: }
1.449 matthew 5877: }
5878:
1.12 www 5879: # --------------------------------------------------------------- put interface
5880:
5881: sub put {
1.134 albertel 5882: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5883: if (!$udomain) { $udomain=$env{'user.domain'}; }
5884: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5885: my $uhome=&homeserver($uname,$udomain);
1.12 www 5886: my $items='';
1.800 albertel 5887: foreach my $item (keys(%$storehash)) {
5888: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5889: }
1.12 www 5890: $items=~s/\&$//;
1.134 albertel 5891: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5892: }
5893:
1.631 albertel 5894: # ------------------------------------------------------------ newput interface
5895:
5896: sub newput {
5897: my ($namespace,$storehash,$udomain,$uname)=@_;
5898: if (!$udomain) { $udomain=$env{'user.domain'}; }
5899: if (!$uname) { $uname=$env{'user.name'}; }
5900: my $uhome=&homeserver($uname,$udomain);
5901: my $items='';
5902: foreach my $key (keys(%$storehash)) {
5903: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5904: }
5905: $items=~s/\&$//;
5906: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5907: }
5908:
5909: # --------------------------------------------------------- putstore interface
5910:
1.524 raeburn 5911: sub putstore {
1.1172.2.59 raeburn 5912: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5913: if (!$udomain) { $udomain=$env{'user.domain'}; }
5914: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5915: my $uhome=&homeserver($uname,$udomain);
5916: my $items='';
1.715 albertel 5917: foreach my $key (keys(%$storehash)) {
5918: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5919: }
1.715 albertel 5920: $items=~s/\&$//;
1.716 albertel 5921: my $esc_symb=&escape($symb);
5922: my $esc_v=&escape($version);
1.715 albertel 5923: my $reply =
1.716 albertel 5924: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5925: $uhome);
1.1172.2.59 raeburn 5926: if (($tolog) && ($reply eq 'ok')) {
5927: my $namevalue='';
5928: foreach my $key (keys(%{$storehash})) {
5929: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5930: }
5931: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5932: '&host='.&escape($perlvar{'lonHostID'}).
5933: '&version='.$esc_v.
5934: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5935: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5936: }
1.715 albertel 5937: if ($reply eq 'unknown_cmd') {
1.716 albertel 5938: # gfall back to way things use to be done
1.715 albertel 5939: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5940: $uname);
1.524 raeburn 5941: }
1.715 albertel 5942: return $reply;
5943: }
5944:
5945: sub old_putstore {
1.716 albertel 5946: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5947: if (!$udomain) { $udomain=$env{'user.domain'}; }
5948: if (!$uname) { $uname=$env{'user.name'}; }
5949: my $uhome=&homeserver($uname,$udomain);
5950: my %newstorehash;
1.800 albertel 5951: foreach my $item (keys(%$storehash)) {
5952: my $key = $version.':'.&escape($symb).':'.$item;
5953: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5954: }
5955: my $items='';
5956: my %allitems = ();
1.800 albertel 5957: foreach my $item (keys(%newstorehash)) {
5958: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5959: my $key = $1.':keys:'.$2;
5960: $allitems{$key} .= $3.':';
5961: }
1.800 albertel 5962: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5963: }
1.800 albertel 5964: foreach my $item (keys(%allitems)) {
5965: $allitems{$item} =~ s/\:$//;
5966: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5967: }
5968: $items=~s/\&$//;
5969: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5970: }
5971:
1.47 www 5972: # ------------------------------------------------------ critical put interface
5973:
5974: sub cput {
1.134 albertel 5975: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5976: if (!$udomain) { $udomain=$env{'user.domain'}; }
5977: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5978: my $uhome=&homeserver($uname,$udomain);
1.47 www 5979: my $items='';
1.800 albertel 5980: foreach my $item (keys(%$storehash)) {
5981: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5982: }
1.47 www 5983: $items=~s/\&$//;
1.134 albertel 5984: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5985: }
5986:
5987: # -------------------------------------------------------------- eget interface
5988:
5989: sub eget {
1.133 albertel 5990: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5991: my $items='';
1.800 albertel 5992: foreach my $item (@$storearr) {
5993: $items.=&escape($item).'&';
1.191 harris41 5994: }
1.12 www 5995: $items=~s/\&$//;
1.620 albertel 5996: if (!$udomain) { $udomain=$env{'user.domain'}; }
5997: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5998: my $uhome=&homeserver($uname,$udomain);
5999: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6000: my @pairs=split(/\&/,$rep);
6001: my %returnhash=();
1.42 www 6002: my $i=0;
1.800 albertel 6003: foreach my $item (@$storearr) {
6004: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6005: $i++;
1.191 harris41 6006: }
1.12 www 6007: return %returnhash;
6008: }
6009:
1.667 albertel 6010: # ------------------------------------------------------------ tmpput interface
6011: sub tmpput {
1.802 raeburn 6012: my ($storehash,$server,$context)=@_;
1.667 albertel 6013: my $items='';
1.800 albertel 6014: foreach my $item (keys(%$storehash)) {
6015: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6016: }
6017: $items=~s/\&$//;
1.802 raeburn 6018: if (defined($context)) {
6019: $items .= ':'.&escape($context);
6020: }
1.667 albertel 6021: return &reply("tmpput:$items",$server);
6022: }
6023:
6024: # ------------------------------------------------------------ tmpget interface
6025: sub tmpget {
1.688 albertel 6026: my ($token,$server)=@_;
6027: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6028: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6029: my %returnhash;
6030: foreach my $item (split(/\&/,$rep)) {
6031: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6032: next if ($key =~ /^error: 2 /);
1.667 albertel 6033: $returnhash{&unescape($key)}=&thaw_unescape($value);
6034: }
6035: return %returnhash;
6036: }
6037:
1.1113 raeburn 6038: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6039: sub tmpdel {
6040: my ($token,$server)=@_;
6041: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6042: return &reply("tmpdel:$token",$server);
6043: }
6044:
1.1172.2.13 raeburn 6045: # ------------------------------------------------------------ get_timebased_id
6046:
6047: sub get_timebased_id {
6048: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6049: $maxtries) = @_;
6050: my ($newid,$error,$dellock);
6051: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6052: return ('','ok','invalid call to get suffix');
6053: }
6054:
6055: # set defaults for any optional args for which values were not supplied
6056: if ($who eq '') {
6057: $who = $env{'user.name'}.':'.$env{'user.domain'};
6058: }
6059: if (!$locktries) {
6060: $locktries = 3;
6061: }
6062: if (!$maxtries) {
6063: $maxtries = 10;
6064: }
6065:
6066: if (($cdom eq '') || ($cnum eq '')) {
6067: if ($env{'request.course.id'}) {
6068: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6069: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6070: }
6071: if (($cdom eq '') || ($cnum eq '')) {
6072: return ('','ok','call to get suffix not in course context');
6073: }
6074: }
6075:
6076: # construct locking item
6077: my $lockhash = {
6078: $prefix."\0".'locked_'.$keyid => $who,
6079: };
6080: my $tries = 0;
6081:
6082: # attempt to get lock on nohist_$namespace file
6083: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6084: while (($gotlock ne 'ok') && $tries <$locktries) {
6085: $tries ++;
6086: sleep 1;
6087: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6088: }
6089:
6090: # attempt to get unique identifier, based on current timestamp
6091: if ($gotlock eq 'ok') {
6092: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6093: my $id = time;
6094: $newid = $id;
1.1172.2.56 raeburn 6095: if ($idtype eq 'addcode') {
6096: $newid .= &sixnum_code();
6097: }
1.1172.2.13 raeburn 6098: my $idtries = 0;
6099: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6100: if ($idtype eq 'concat') {
6101: $newid = $id.$idtries;
1.1172.2.56 raeburn 6102: } elsif ($idtype eq 'addcode') {
6103: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6104: } else {
6105: $newid ++;
6106: }
6107: $idtries ++;
6108: }
6109: if (!exists($inuse{$prefix."\0".$newid})) {
6110: my %new_item = (
6111: $prefix."\0".$newid => $who,
6112: );
6113: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6114: $cdom,$cnum);
6115: if ($putresult ne 'ok') {
6116: undef($newid);
6117: $error = 'error saving new item: '.$putresult;
6118: }
6119: } else {
1.1172.2.56 raeburn 6120: undef($newid);
1.1172.2.13 raeburn 6121: $error = ('error: no unique suffix available for the new item ');
6122: }
6123: # remove lock
6124: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6125: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6126: } else {
6127: $error = "error: could not obtain lockfile\n";
6128: $dellock = 'ok';
1.1172.2.58 raeburn 6129: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6130: $dellock = 'nolock';
6131: }
1.1172.2.13 raeburn 6132: }
6133: return ($newid,$dellock,$error);
6134: }
6135:
1.1172.2.56 raeburn 6136: sub sixnum_code {
6137: my $code;
6138: for (0..6) {
6139: $code .= int( rand(9) );
6140: }
6141: return $code;
6142: }
6143:
1.765 albertel 6144: # -------------------------------------------------- portfolio access checking
6145:
6146: sub portfolio_access {
1.766 albertel 6147: my ($requrl) = @_;
1.765 albertel 6148: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6149: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6150: if ($result) {
6151: my %setters;
6152: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6153: my ($startblock,$endblock) =
6154: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6155: if ($startblock && $endblock) {
6156: return 'B';
6157: }
6158: } else {
6159: my ($startblock,$endblock) =
6160: &Apache::loncommon::blockcheck(\%setters,'port');
6161: if ($startblock && $endblock) {
6162: return 'B';
6163: }
6164: }
6165: }
1.765 albertel 6166: if ($result eq 'ok') {
1.766 albertel 6167: return 'F';
1.765 albertel 6168: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6169: return 'A';
1.765 albertel 6170: }
1.766 albertel 6171: return '';
1.765 albertel 6172: }
6173:
6174: sub get_portfolio_access {
1.767 albertel 6175: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6176:
6177: if (!ref($access_hash)) {
6178: my $current_perms = &get_portfile_permissions($udom,$unum);
6179: my %access_controls = &get_access_controls($current_perms,$group,
6180: $file_name);
6181: $access_hash = $access_controls{$file_name};
6182: }
6183:
1.765 albertel 6184: my ($public,$guest,@domains,@users,@courses,@groups);
6185: my $now = time;
6186: if (ref($access_hash) eq 'HASH') {
6187: foreach my $key (keys(%{$access_hash})) {
6188: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6189: if ($start > $now) {
6190: next;
6191: }
6192: if ($end && $end<$now) {
6193: next;
6194: }
6195: if ($scope eq 'public') {
6196: $public = $key;
6197: last;
6198: } elsif ($scope eq 'guest') {
6199: $guest = $key;
6200: } elsif ($scope eq 'domains') {
6201: push(@domains,$key);
6202: } elsif ($scope eq 'users') {
6203: push(@users,$key);
6204: } elsif ($scope eq 'course') {
6205: push(@courses,$key);
6206: } elsif ($scope eq 'group') {
6207: push(@groups,$key);
6208: }
6209: }
6210: if ($public) {
6211: return 'ok';
6212: }
6213: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6214: if ($guest) {
6215: return $guest;
6216: }
6217: } else {
6218: if (@domains > 0) {
6219: foreach my $domkey (@domains) {
6220: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6221: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6222: return 'ok';
6223: }
6224: }
6225: }
6226: }
6227: if (@users > 0) {
6228: foreach my $userkey (@users) {
1.865 raeburn 6229: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6230: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6231: if (ref($item) eq 'HASH') {
6232: if (($item->{'uname'} eq $env{'user.name'}) &&
6233: ($item->{'udom'} eq $env{'user.domain'})) {
6234: return 'ok';
6235: }
6236: }
6237: }
6238: }
1.765 albertel 6239: }
6240: }
6241: my %roleshash;
6242: my @courses_and_groups = @courses;
6243: push(@courses_and_groups,@groups);
6244: if (@courses_and_groups > 0) {
6245: my (%allgroups,%allroles);
6246: my ($start,$end,$role,$sec,$group);
6247: foreach my $envkey (%env) {
1.1060 raeburn 6248: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6249: my $cid = $2.'_'.$3;
6250: if ($1 eq 'gr') {
6251: $group = $4;
6252: $allgroups{$cid}{$group} = $env{$envkey};
6253: } else {
6254: if ($4 eq '') {
6255: $sec = 'none';
6256: } else {
6257: $sec = $4;
6258: }
6259: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6260: }
1.811 albertel 6261: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6262: my $cid = $2.'_'.$3;
6263: if ($4 eq '') {
6264: $sec = 'none';
6265: } else {
6266: $sec = $4;
6267: }
6268: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6269: }
6270: }
6271: if (keys(%allroles) == 0) {
6272: return;
6273: }
6274: foreach my $key (@courses_and_groups) {
6275: my %content = %{$$access_hash{$key}};
6276: my $cnum = $content{'number'};
6277: my $cdom = $content{'domain'};
6278: my $cid = $cdom.'_'.$cnum;
6279: if (!exists($allroles{$cid})) {
6280: next;
6281: }
6282: foreach my $role_id (keys(%{$content{'roles'}})) {
6283: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6284: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6285: my @status = @{$content{'roles'}{$role_id}{'access'}};
6286: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6287: foreach my $role (keys(%{$allroles{$cid}})) {
6288: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6289: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6290: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6291: if (grep/^all$/,@sections) {
6292: return 'ok';
6293: } else {
6294: if (grep/^$sec$/,@sections) {
6295: return 'ok';
6296: }
6297: }
6298: }
6299: }
6300: if (keys(%{$allgroups{$cid}}) == 0) {
6301: if (grep/^none$/,@groups) {
6302: return 'ok';
6303: }
6304: } else {
6305: if (grep/^all$/,@groups) {
6306: return 'ok';
6307: }
6308: foreach my $group (keys(%{$allgroups{$cid}})) {
6309: if (grep/^$group$/,@groups) {
6310: return 'ok';
6311: }
6312: }
6313: }
6314: }
6315: }
6316: }
6317: }
6318: }
6319: if ($guest) {
6320: return $guest;
6321: }
6322: }
6323: }
6324: return;
6325: }
6326:
6327: sub course_group_datechecker {
6328: my ($dates,$now,$status) = @_;
6329: my ($start,$end) = split(/\./,$dates);
6330: if (!$start && !$end) {
6331: return 'ok';
6332: }
6333: if (grep/^active$/,@{$status}) {
6334: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6335: return 'ok';
6336: }
6337: }
6338: if (grep/^previous$/,@{$status}) {
6339: if ($end > $now ) {
6340: return 'ok';
6341: }
6342: }
6343: if (grep/^future$/,@{$status}) {
6344: if ($start > $now) {
6345: return 'ok';
6346: }
6347: }
6348: return;
6349: }
6350:
6351: sub parse_portfolio_url {
6352: my ($url) = @_;
6353:
6354: my ($type,$udom,$unum,$group,$file_name);
6355:
1.823 albertel 6356: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6357: $type = 1;
6358: $udom = $1;
6359: $unum = $2;
6360: $file_name = $3;
1.823 albertel 6361: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6362: $type = 2;
6363: $udom = $1;
6364: $unum = $2;
6365: $group = $3;
6366: $file_name = $3.'/'.$4;
6367: }
6368: if (wantarray) {
6369: return ($type,$udom,$unum,$file_name,$group);
6370: }
6371: return $type;
6372: }
6373:
6374: sub is_portfolio_url {
6375: my ($url) = @_;
6376: return scalar(&parse_portfolio_url($url));
6377: }
6378:
1.798 raeburn 6379: sub is_portfolio_file {
6380: my ($file) = @_;
1.820 raeburn 6381: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6382: return 1;
6383: }
6384: return;
6385: }
6386:
1.976 raeburn 6387: sub usertools_access {
1.1084 raeburn 6388: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6389: my ($access,%tools);
6390: if ($context eq '') {
6391: $context = 'tools';
6392: }
6393: if ($context eq 'requestcourses') {
6394: %tools = (
6395: official => 1,
6396: unofficial => 1,
1.1006 raeburn 6397: community => 1,
1.1172.2.37 raeburn 6398: textbook => 1,
1.985 raeburn 6399: );
1.1172.2.9 raeburn 6400: } elsif ($context eq 'requestauthor') {
6401: %tools = (
6402: requestauthor => 1,
6403: );
1.985 raeburn 6404: } else {
6405: %tools = (
6406: aboutme => 1,
6407: blog => 1,
1.1172.2.6 raeburn 6408: webdav => 1,
1.985 raeburn 6409: portfolio => 1,
6410: );
6411: }
1.976 raeburn 6412: return if (!defined($tools{$tool}));
6413:
1.1172.2.35 raeburn 6414: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6415: $udom = $env{'user.domain'};
6416: $uname = $env{'user.name'};
6417: }
6418:
1.978 raeburn 6419: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6420: if ($action ne 'reload') {
1.985 raeburn 6421: if ($context eq 'requestcourses') {
6422: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6423: } elsif ($context eq 'requestauthor') {
6424: return $env{'environment.canrequest.author'};
1.985 raeburn 6425: } else {
6426: return $env{'environment.availabletools.'.$tool};
6427: }
6428: }
1.976 raeburn 6429: }
6430:
1.1172.2.9 raeburn 6431: my ($toolstatus,$inststatus,$envkey);
6432: if ($context eq 'requestauthor') {
6433: $envkey = $context;
6434: } else {
6435: $envkey = $context.'.'.$tool;
6436: }
1.976 raeburn 6437:
1.985 raeburn 6438: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6439: ($action ne 'reload')) {
1.1172.2.9 raeburn 6440: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6441: $inststatus = $env{'environment.inststatus'};
6442: } else {
1.1084 raeburn 6443: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6444: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6445: $inststatus = $userenvref->{'inststatus'};
6446: } else {
1.1172.2.9 raeburn 6447: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6448: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6449: $inststatus = $userenv{'inststatus'};
6450: }
1.976 raeburn 6451: }
6452:
6453: if ($toolstatus ne '') {
6454: if ($toolstatus) {
6455: $access = 1;
6456: } else {
6457: $access = 0;
6458: }
6459: return $access;
6460: }
6461:
1.1084 raeburn 6462: my ($is_adv,%domdef);
6463: if (ref($is_advref) eq 'HASH') {
6464: $is_adv = $is_advref->{'is_adv'};
6465: } else {
6466: $is_adv = &is_advanced_user($udom,$uname);
6467: }
6468: if (ref($domdefref) eq 'HASH') {
6469: %domdef = %{$domdefref};
6470: } else {
6471: %domdef = &get_domain_defaults($udom);
6472: }
1.976 raeburn 6473: if (ref($domdef{$tool}) eq 'HASH') {
6474: if ($is_adv) {
6475: if ($domdef{$tool}{'_LC_adv'} ne '') {
6476: if ($domdef{$tool}{'_LC_adv'}) {
6477: $access = 1;
6478: } else {
6479: $access = 0;
6480: }
6481: return $access;
6482: }
6483: }
6484: if ($inststatus ne '') {
6485: my ($hasaccess,$hasnoaccess);
6486: foreach my $affiliation (split(/:/,$inststatus)) {
6487: if ($domdef{$tool}{$affiliation} ne '') {
6488: if ($domdef{$tool}{$affiliation}) {
6489: $hasaccess = 1;
6490: } else {
6491: $hasnoaccess = 1;
6492: }
6493: }
6494: }
6495: if ($hasaccess || $hasnoaccess) {
6496: if ($hasaccess) {
6497: $access = 1;
6498: } elsif ($hasnoaccess) {
6499: $access = 0;
6500: }
6501: return $access;
6502: }
6503: } else {
6504: if ($domdef{$tool}{'default'} ne '') {
6505: if ($domdef{$tool}{'default'}) {
6506: $access = 1;
6507: } elsif ($domdef{$tool}{'default'} == 0) {
6508: $access = 0;
6509: }
6510: return $access;
6511: }
6512: }
6513: } else {
1.1172.2.6 raeburn 6514: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6515: $access = 1;
6516: } else {
6517: $access = 0;
6518: }
1.976 raeburn 6519: return $access;
6520: }
6521: }
6522:
1.1050 raeburn 6523: sub is_course_owner {
6524: my ($cdom,$cnum,$udom,$uname) = @_;
6525: if (($udom eq '') || ($uname eq '')) {
6526: $udom = $env{'user.domain'};
6527: $uname = $env{'user.name'};
6528: }
6529: unless (($udom eq '') || ($uname eq '')) {
6530: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6531: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6532: return 1;
6533: } else {
6534: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6535: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6536: return 1;
6537: }
6538: }
6539: }
6540: }
6541: return;
6542: }
6543:
1.976 raeburn 6544: sub is_advanced_user {
6545: my ($udom,$uname) = @_;
1.1085 raeburn 6546: if ($udom ne '' && $uname ne '') {
6547: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6548: if (wantarray) {
6549: return ($env{'user.adv'},$env{'user.author'});
6550: } else {
6551: return $env{'user.adv'};
6552: }
1.1085 raeburn 6553: }
6554: }
1.976 raeburn 6555: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6556: my %allroles;
1.1128 raeburn 6557: my ($is_adv,$is_author);
1.976 raeburn 6558: foreach my $role (keys(%roleshash)) {
6559: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6560: my $area = '/'.$tdomain.'/'.$trest;
6561: if ($sec ne '') {
6562: $area .= '/'.$sec;
6563: }
6564: if (($area ne '') && ($trole ne '')) {
6565: my $spec=$trole.'.'.$area;
6566: if ($trole =~ /^cr\//) {
6567: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6568: } elsif ($trole ne 'gr') {
6569: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6570: }
1.1128 raeburn 6571: if ($trole eq 'au') {
6572: $is_author = 1;
6573: }
1.976 raeburn 6574: }
6575: }
6576: foreach my $role (keys(%allroles)) {
6577: last if ($is_adv);
6578: foreach my $item (split(/:/,$allroles{$role})) {
6579: if ($item ne '') {
6580: my ($privilege,$restrictions)=split(/&/,$item);
6581: if ($privilege eq 'adv') {
6582: $is_adv = 1;
6583: last;
6584: }
6585: }
6586: }
6587: }
1.1128 raeburn 6588: if (wantarray) {
6589: return ($is_adv,$is_author);
6590: }
1.976 raeburn 6591: return $is_adv;
6592: }
1.798 raeburn 6593:
1.1035 raeburn 6594: sub check_can_request {
1.1036 raeburn 6595: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6596: my $canreq = 0;
6597: my ($types,$typename) = &Apache::loncommon::course_types();
6598: my @options = ('approval','validate','autolimit');
6599: my $optregex = join('|',@options);
6600: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6601: foreach my $type (@{$types}) {
6602: if (&usertools_access($env{'user.name'},
6603: $env{'user.domain'},
6604: $type,undef,'requestcourses')) {
6605: $canreq ++;
1.1036 raeburn 6606: if (ref($request_domains) eq 'HASH') {
6607: push(@{$request_domains->{$type}},$env{'user.domain'});
6608: }
1.1035 raeburn 6609: if ($dom eq $env{'user.domain'}) {
6610: $can_request->{$type} = 1;
6611: }
6612: }
6613: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6614: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6615: if (@curr > 0) {
1.1036 raeburn 6616: foreach my $item (@curr) {
6617: if (ref($request_domains) eq 'HASH') {
6618: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6619: if ($otherdom ne '') {
6620: if (ref($request_domains->{$type}) eq 'ARRAY') {
6621: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6622: push(@{$request_domains->{$type}},$otherdom);
6623: }
6624: } else {
6625: push(@{$request_domains->{$type}},$otherdom);
6626: }
6627: }
6628: }
6629: }
6630: unless($dom eq $env{'user.domain'}) {
6631: $canreq ++;
1.1035 raeburn 6632: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6633: $can_request->{$type} = 1;
6634: }
6635: }
6636: }
6637: }
6638: }
6639: }
6640: return $canreq;
6641: }
6642:
1.341 www 6643: # ---------------------------------------------- Custom access rule evaluation
6644:
6645: sub customaccess {
6646: my ($priv,$uri)=@_;
1.807 albertel 6647: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6648: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6649: $udom = &LONCAPA::clean_domain($udom);
6650: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6651: my $access=0;
1.800 albertel 6652: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6653: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6654: if ($type eq 'user') {
6655: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6656: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6657: if ($tdom) {
6658: if ($tdom ne $env{'user.domain'}) { next; }
6659: }
1.896 albertel 6660: if ($tuname) {
6661: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6662: }
6663: $access=($effect eq 'allow');
6664: last;
6665: }
6666: } else {
6667: if ($role) {
6668: if ($role ne $urole) { next; }
6669: }
6670: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6671: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6672: if ($tdom) {
6673: if ($tdom ne $udom) { next; }
6674: }
6675: if ($tcrs) {
6676: if ($tcrs ne $ucrs) { next; }
6677: }
6678: if ($tsec) {
6679: if ($tsec ne $usec) { next; }
6680: }
6681: $access=($effect eq 'allow');
6682: last;
6683: }
6684: if ($realm eq '' && $role eq '') {
6685: $access=($effect eq 'allow');
6686: }
1.402 bowersj2 6687: }
1.341 www 6688: }
6689: return $access;
6690: }
6691:
1.103 harris41 6692: # ------------------------------------------------- Check for a user privilege
1.12 www 6693:
6694: sub allowed {
1.810 raeburn 6695: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6696: my $ver_orguri=$uri;
1.439 www 6697: $uri=&deversion($uri);
1.152 www 6698: my $orguri=$uri;
1.52 www 6699: $uri=&declutter($uri);
1.809 raeburn 6700:
1.810 raeburn 6701: if ($priv eq 'evb') {
6702: # Evade communication block restrictions for specified role in a course
6703: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6704: return $1;
6705: } else {
6706: return;
6707: }
6708: }
6709:
1.620 albertel 6710: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6711: # Free bre access to adm and meta resources
1.775 albertel 6712: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6713: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6714: && ($priv eq 'bre')) {
1.14 www 6715: return 'F';
1.159 www 6716: }
6717:
1.545 banghart 6718: # Free bre access to user's own portfolio contents
1.714 raeburn 6719: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6720: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6721: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6722: my %setters;
6723: my ($startblock,$endblock) =
6724: &Apache::loncommon::blockcheck(\%setters,'port');
6725: if ($startblock && $endblock) {
6726: return 'B';
6727: } else {
6728: return 'F';
6729: }
1.545 banghart 6730: }
6731:
1.762 raeburn 6732: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6733: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6734: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6735: if (exists($env{'request.course.id'})) {
6736: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6737: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6738: if (($domain eq $cdom) && ($name eq $cnum)) {
6739: my $courseprivid=$env{'request.course.id'};
6740: $courseprivid=~s/\_/\//;
6741: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6742: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6743: return $1;
1.762 raeburn 6744: } else {
6745: if ($env{'request.course.sec'}) {
6746: $courseprivid.='/'.$env{'request.course.sec'};
6747: }
6748: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6749: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6750: return $2;
6751: }
1.714 raeburn 6752: }
6753: }
6754: }
6755: }
6756:
1.159 www 6757: # Free bre to public access
6758:
6759: if ($priv eq 'bre') {
1.238 www 6760: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6761: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6762: return 'F';
6763: }
1.238 www 6764: if ($copyright eq 'priv') {
6765: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6766: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6767: return '';
6768: }
6769: }
6770: if ($copyright eq 'domain') {
6771: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6772: unless (($env{'user.domain'} eq $1) ||
6773: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6774: return '';
6775: }
1.262 matthew 6776: }
1.620 albertel 6777: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6778: # Library role, so allow browsing of resources in this domain.
6779: return 'F';
1.238 www 6780: }
1.341 www 6781: if ($copyright eq 'custom') {
6782: unless (&customaccess($priv,$uri)) { return ''; }
6783: }
1.14 www 6784: }
1.264 matthew 6785: # Domain coordinator is trying to create a course
1.620 albertel 6786: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6787: # uri is the requested domain in this case.
6788: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6789: # a role of dc for the domain in question.
1.620 albertel 6790: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6791: }
1.29 www 6792:
1.52 www 6793: my $thisallowed='';
6794: my $statecond=0;
6795: my $courseprivid='';
6796:
1.1039 raeburn 6797: my $ownaccess;
1.1043 raeburn 6798: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6799: if (($priv eq 'bro') && ($env{'user.author'})) {
6800: if ($uri eq '') {
6801: $ownaccess = 1;
6802: } else {
6803: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6804: my $udom = $env{'user.domain'};
6805: my $uname = $env{'user.name'};
6806: if ($uri =~ m{^\Q$udom\E/?$}) {
6807: $ownaccess = 1;
1.1040 raeburn 6808: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6809: unless ($uri =~ m{\.\./}) {
6810: $ownaccess = 1;
6811: }
6812: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6813: my $now = time;
6814: if ($uri =~ m{^([^/]+)/?$}) {
6815: my $adom = $1;
6816: foreach my $key (keys(%env)) {
1.1042 raeburn 6817: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6818: my ($start,$end) = split('.',$env{$key});
6819: if (($now >= $start) && (!$end || $end < $now)) {
6820: $ownaccess = 1;
6821: last;
6822: }
6823: }
6824: }
6825: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6826: my $adom = $1;
6827: my $aname = $2;
1.1042 raeburn 6828: foreach my $role ('ca','aa') {
6829: if ($env{"user.role.$role./$adom/$aname"}) {
6830: my ($start,$end) =
6831: split('.',$env{"user.role.$role./$adom/$aname"});
6832: if (($now >= $start) && (!$end || $end < $now)) {
6833: $ownaccess = 1;
6834: last;
6835: }
1.1039 raeburn 6836: }
6837: }
6838: }
6839: }
6840: }
6841: }
6842: }
6843:
1.52 www 6844: # Course
6845:
1.620 albertel 6846: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6847: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6848: $thisallowed.=$1;
6849: }
1.52 www 6850: }
1.29 www 6851:
1.52 www 6852: # Domain
6853:
1.620 albertel 6854: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6855: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6856: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6857: $thisallowed.=$1;
6858: }
1.12 www 6859: }
1.52 www 6860:
1.1141 raeburn 6861: # User who is not author or co-author might still be able to edit
6862: # resource of an author in the domain (e.g., if Domain Coordinator).
6863: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6864: (&allowed('mdc',$env{'request.course.id'}))) {
6865: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6866: $thisallowed.=$1;
6867: }
6868: }
6869:
1.52 www 6870: # Course: uri itself is a course
1.66 www 6871: my $courseuri=$uri;
6872: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6873: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6874:
1.620 albertel 6875: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6876: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6877: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6878: $thisallowed.=$1;
6879: }
1.12 www 6880: }
1.29 www 6881:
1.665 albertel 6882: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6883: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6884: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6885: $thisallowed='';
1.671 raeburn 6886: my ($match)=&is_on_map($uri);
6887: if ($match) {
6888: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6889: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6890: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6891: if (@blockers > 0) {
6892: $thisallowed = 'B';
6893: } else {
6894: $thisallowed.=$1;
6895: }
1.671 raeburn 6896: }
6897: } else {
1.705 albertel 6898: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6899: if ($refuri) {
6900: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6901: $thisallowed='F';
1.671 raeburn 6902: } else {
6903: $refuri=&declutter($refuri);
6904: my ($match) = &is_on_map($refuri);
6905: if ($match) {
1.1162 raeburn 6906: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6907: if (@blockers > 0) {
6908: $thisallowed = 'B';
6909: } else {
6910: $thisallowed='F';
6911: }
1.671 raeburn 6912: }
1.669 raeburn 6913: }
1.671 raeburn 6914: }
6915: }
1.314 www 6916: }
1.492 albertel 6917:
1.766 albertel 6918: if ($priv eq 'bre'
6919: && $thisallowed ne 'F'
6920: && $thisallowed ne '2'
6921: && &is_portfolio_url($uri)) {
6922: $thisallowed = &portfolio_access($uri);
6923: }
6924:
1.52 www 6925: # Full access at system, domain or course-wide level? Exit.
1.29 www 6926: if ($thisallowed=~/F/) {
6927: return 'F';
6928: }
6929:
1.52 www 6930: # If this is generating or modifying users, exit with special codes
1.29 www 6931:
1.643 www 6932: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6933: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6934: my ($audom,$auname)=split('/',$uri);
1.643 www 6935: # no author name given, so this just checks on the general right to make a co-author in this domain
6936: unless ($auname) { return $thisallowed; }
6937: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6938: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6939: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6940: ($audom ne $env{'request.role.domain'}))) { return ''; }
6941: }
1.52 www 6942: return $thisallowed;
6943: }
6944: #
1.103 harris41 6945: # Gathered so far: system, domain and course wide privileges
1.52 www 6946: #
6947: # Course: See if uri or referer is an individual resource that is part of
6948: # the course
6949:
1.620 albertel 6950: if ($env{'request.course.id'}) {
1.232 www 6951:
1.620 albertel 6952: $courseprivid=$env{'request.course.id'};
6953: if ($env{'request.course.sec'}) {
6954: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6955: }
6956: $courseprivid=~s/\_/\//;
6957: my $checkreferer=1;
1.232 www 6958: my ($match,$cond)=&is_on_map($uri);
6959: if ($match) {
6960: $statecond=$cond;
1.620 albertel 6961: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6962: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6963: my $value = $1;
6964: if ($priv eq 'bre') {
6965: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6966: if (@blockers > 0) {
6967: $thisallowed = 'B';
6968: } else {
6969: $thisallowed.=$value;
6970: }
6971: } else {
6972: $thisallowed.=$value;
6973: }
1.52 www 6974: $checkreferer=0;
6975: }
1.29 www 6976: }
1.83 www 6977:
1.148 www 6978: if ($checkreferer) {
1.620 albertel 6979: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6980: unless ($refuri) {
1.800 albertel 6981: foreach my $key (keys(%env)) {
6982: if ($key=~/^httpref\..*\*/) {
6983: my $pattern=$key;
1.156 www 6984: $pattern=~s/^httpref\.\/res\///;
1.148 www 6985: $pattern=~s/\*/\[\^\/\]\+/g;
6986: $pattern=~s/\//\\\//g;
1.152 www 6987: if ($orguri=~/$pattern/) {
1.800 albertel 6988: $refuri=$env{$key};
1.148 www 6989: }
6990: }
1.191 harris41 6991: }
1.148 www 6992: }
1.232 www 6993:
1.148 www 6994: if ($refuri) {
1.152 www 6995: $refuri=&declutter($refuri);
1.232 www 6996: my ($match,$cond)=&is_on_map($refuri);
6997: if ($match) {
6998: my $refstatecond=$cond;
1.620 albertel 6999: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7000: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7001: my $value = $1;
7002: if ($priv eq 'bre') {
7003: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7004: if (@blockers > 0) {
7005: $thisallowed = 'B';
7006: } else {
7007: $thisallowed.=$value;
7008: }
7009: } else {
7010: $thisallowed.=$value;
7011: }
1.53 www 7012: $uri=$refuri;
7013: $statecond=$refstatecond;
1.52 www 7014: }
7015: }
1.148 www 7016: }
1.29 www 7017: }
1.52 www 7018: }
1.29 www 7019:
1.52 www 7020: #
1.103 harris41 7021: # Gathered now: all privileges that could apply, and condition number
1.52 www 7022: #
7023: #
7024: # Full or no access?
7025: #
1.29 www 7026:
1.52 www 7027: if ($thisallowed=~/F/) {
7028: return 'F';
7029: }
1.29 www 7030:
1.52 www 7031: unless ($thisallowed) {
7032: return '';
7033: }
1.29 www 7034:
1.52 www 7035: # Restrictions exist, deal with them
7036: #
7037: # C:according to course preferences
7038: # R:according to resource settings
7039: # L:unless locked
7040: # X:according to user session state
7041: #
7042:
7043: # Possibly locked functionality, check all courses
1.54 www 7044: # Locks might take effect only after 10 minutes cache expiration for other
7045: # courses, and 2 minutes for current course
1.52 www 7046:
7047: my $envkey;
7048: if ($thisallowed=~/L/) {
1.1000 raeburn 7049: foreach $envkey (keys(%env)) {
1.54 www 7050: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7051: my $courseid=$2;
7052: my $roleid=$1.'.'.$2;
1.92 www 7053: $courseid=~s/^\///;
1.54 www 7054: my $expiretime=600;
1.620 albertel 7055: if ($env{'request.role'} eq $roleid) {
1.54 www 7056: $expiretime=120;
7057: }
7058: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7059: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7060: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7061: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7062: }
1.620 albertel 7063: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7064: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7065: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7066: &log($env{'user.domain'},$env{'user.name'},
7067: $env{'user.home'},
1.57 www 7068: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7069: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7070: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7071: return '';
7072: }
7073: }
1.620 albertel 7074: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7075: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7076: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7077: &log($env{'user.domain'},$env{'user.name'},
7078: $env{'user.home'},
1.57 www 7079: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7080: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7081: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7082: return '';
7083: }
7084: }
7085: }
1.29 www 7086: }
1.52 www 7087: }
7088:
7089: #
7090: # Rest of the restrictions depend on selected course
7091: #
7092:
1.620 albertel 7093: unless ($env{'request.course.id'}) {
1.766 albertel 7094: if ($thisallowed eq 'A') {
7095: return 'A';
1.814 raeburn 7096: } elsif ($thisallowed eq 'B') {
7097: return 'B';
1.766 albertel 7098: } else {
7099: return '1';
7100: }
1.52 www 7101: }
1.29 www 7102:
1.52 www 7103: #
7104: # Now user is definitely in a course
7105: #
1.53 www 7106:
7107:
7108: # Course preferences
7109:
7110: if ($thisallowed=~/C/) {
1.620 albertel 7111: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7112: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7113: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7114: =~/\Q$rolecode\E/) {
1.1103 raeburn 7115: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7116: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7117: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7118: $env{'request.course.id'});
7119: }
1.237 www 7120: return '';
7121: }
7122:
1.620 albertel 7123: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7124: =~/\Q$unamedom\E/) {
1.1103 raeburn 7125: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7126: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7127: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7128: $env{'request.course.id'});
7129: }
1.54 www 7130: return '';
7131: }
1.53 www 7132: }
7133:
7134: # Resource preferences
7135:
7136: if ($thisallowed=~/R/) {
1.620 albertel 7137: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7138: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7139: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7140: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7141: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7142: }
7143: return '';
1.54 www 7144: }
1.53 www 7145: }
1.30 www 7146:
1.246 www 7147: # Restricted by state or randomout?
1.30 www 7148:
1.52 www 7149: if ($thisallowed=~/X/) {
1.620 albertel 7150: if ($env{'acc.randomout'}) {
1.579 albertel 7151: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7152: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7153: return '';
7154: }
1.247 www 7155: }
7156: if (&condval($statecond)) {
1.52 www 7157: return '2';
7158: } else {
7159: return '';
7160: }
7161: }
1.30 www 7162:
1.766 albertel 7163: if ($thisallowed eq 'A') {
7164: return 'A';
1.814 raeburn 7165: } elsif ($thisallowed eq 'B') {
7166: return 'B';
1.766 albertel 7167: }
1.52 www 7168: return 'F';
1.232 www 7169: }
1.1162 raeburn 7170:
1.1172.2.13 raeburn 7171: # ------------------------------------------- Check construction space access
7172:
7173: sub constructaccess {
7174: my ($url,$setpriv)=@_;
7175:
7176: # We do not allow editing of previous versions of files
7177: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7178:
7179: # Get username and domain from URL
7180: my ($ownername,$ownerdomain,$ownerhome);
7181:
7182: ($ownerdomain,$ownername) =
7183: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7184:
7185: # The URL does not really point to any authorspace, forget it
7186: unless (($ownername) && ($ownerdomain)) { return ''; }
7187:
7188: # Now we need to see if the user has access to the authorspace of
7189: # $ownername at $ownerdomain
7190:
7191: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7192: # Real author for this?
7193: $ownerhome = $env{'user.home'};
7194: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7195: return ($ownername,$ownerdomain,$ownerhome);
7196: }
7197: } else {
7198: # Co-author for this?
7199: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7200: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7201: $ownerhome = &homeserver($ownername,$ownerdomain);
7202: return ($ownername,$ownerdomain,$ownerhome);
7203: }
7204: }
7205:
7206: # We don't have any access right now. If we are not possibly going to do anything about this,
7207: # we might as well leave
7208: unless ($setpriv) { return ''; }
7209:
7210: # Backdoor access?
7211: my $allowed=&allowed('eco',$ownerdomain);
7212: # Nope
7213: unless ($allowed) { return ''; }
7214: # Looks like we may have access, but could be locked by the owner of the construction space
7215: if ($allowed eq 'U') {
7216: my %blocked=&get('environment',['domcoord.author'],
7217: $ownerdomain,$ownername);
7218: # Is blocked by owner
7219: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7220: }
7221: if (($allowed eq 'F') || ($allowed eq 'U')) {
7222: # Grant temporary access
7223: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7224: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7225: if (!$update) { $update = $then; }
7226: my $refresh=$env{'user.refresh.time'};
7227: if (!$refresh) { $refresh = $update; }
7228: my $now = time;
7229: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7230: $now,'ca','constructaccess');
7231: $ownerhome = &homeserver($ownername,$ownerdomain);
7232: return($ownername,$ownerdomain,$ownerhome);
7233: }
7234: # No business here
7235: return '';
7236: }
7237:
1.1162 raeburn 7238: sub get_comm_blocks {
7239: my ($cdom,$cnum) = @_;
7240: if ($cdom eq '' || $cnum eq '') {
7241: return unless ($env{'request.course.id'});
7242: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7243: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7244: }
7245: my %commblocks;
7246: my $hashid=$cdom.'_'.$cnum;
7247: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7248: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7249: %commblocks = %{$blocksref};
7250: } else {
7251: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7252: my $cachetime = 600;
7253: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7254: }
7255: return %commblocks;
7256: }
7257:
7258: sub has_comm_blocking {
7259: my ($priv,$symb,$uri,$blocks) = @_;
7260: return unless ($env{'request.course.id'});
7261: return unless ($priv eq 'bre');
7262: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7263: my %commblocks;
7264: if (ref($blocks) eq 'HASH') {
7265: %commblocks = %{$blocks};
7266: } else {
7267: %commblocks = &get_comm_blocks();
7268: }
7269: return unless (keys(%commblocks) > 0);
7270: if (!$symb) { $symb=&symbread($uri,1); }
7271: my ($map,$resid,undef)=&decode_symb($symb);
7272: my %tocheck = (
7273: maps => $map,
7274: resources => $symb,
7275: );
7276: my @blockers;
7277: my $now = time;
1.1163 raeburn 7278: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7279: foreach my $block (keys(%commblocks)) {
7280: if ($block =~ /^(\d+)____(\d+)$/) {
7281: my ($start,$end) = ($1,$2);
7282: if ($start <= $now && $end >= $now) {
7283: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7284: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7285: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7286: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7287: unless (grep(/^\Q$block\E$/,@blockers)) {
7288: push(@blockers,$block);
7289: }
7290: }
7291: }
7292: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7293: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7294: unless (grep(/^\Q$block\E$/,@blockers)) {
7295: push(@blockers,$block);
7296: }
7297: }
7298: }
7299: }
7300: }
7301: }
7302: } elsif ($block =~ /^firstaccess____(.+)$/) {
7303: my $item = $1;
1.1163 raeburn 7304: my @to_test;
1.1162 raeburn 7305: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7306: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7307: my $check_interval;
7308: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7309: my @interval;
7310: my $type = 'map';
7311: if ($item eq 'course') {
7312: $type = 'course';
7313: @interval=&EXT("resource.0.interval");
7314: } else {
7315: if ($item =~ /___\d+___/) {
7316: $type = 'resource';
7317: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7318: if (ref($navmap)) {
7319: my $res = $navmap->getBySymb($item);
7320: push(@to_test,$res);
7321: }
1.1162 raeburn 7322: } else {
7323: my $mapsymb = &symbread($item,1);
7324: if ($mapsymb) {
7325: if (ref($navmap)) {
7326: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7327: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7328: foreach my $res (@to_test) {
1.1162 raeburn 7329: my $symb = $res->symb();
7330: next if ($symb eq $mapsymb);
7331: if ($symb ne '') {
7332: @interval=&EXT("resource.0.interval",$symb);
7333: last;
7334: }
7335: }
7336: }
7337: }
7338: }
7339: }
7340: if ($interval[0] =~ /\d+/) {
7341: my $first_access;
7342: if ($type eq 'resource') {
7343: $first_access=&get_first_access($interval[1],$item);
7344: } elsif ($type eq 'map') {
7345: $first_access=&get_first_access($interval[1],undef,$item);
7346: } else {
7347: $first_access=&get_first_access($interval[1]);
7348: }
7349: if ($first_access) {
7350: my $timesup = $first_access+$interval[0];
7351: if ($timesup > $now) {
1.1163 raeburn 7352: foreach my $res (@to_test) {
7353: if ($res->is_problem()) {
7354: if ($res->completable()) {
7355: unless (grep(/^\Q$block\E$/,@blockers)) {
7356: push(@blockers,$block);
7357: }
7358: last;
7359: }
7360: }
1.1162 raeburn 7361: }
7362: }
7363: }
7364: }
7365: }
7366: }
7367: }
7368: }
7369: }
7370: return @blockers;
7371: }
7372:
7373: sub check_docs_block {
7374: my ($docsblock,$tocheck) =@_;
7375: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7376: return;
7377: }
7378: if (ref($docsblock->{'maps'}) eq 'HASH') {
7379: if ($tocheck->{'maps'}) {
7380: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7381: return 1;
7382: }
7383: }
7384: }
7385: if (ref($docsblock->{'resources'}) eq 'HASH') {
7386: if ($tocheck->{'resources'}) {
7387: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7388: return 1;
7389: }
7390: }
7391: }
7392: return;
7393: }
7394:
1.1133 foxr 7395: #
7396: # Removes the versino from a URI and
7397: # splits it in to its filename and path to the filename.
7398: # Seems like File::Basename could have done this more clearly.
7399: # Parameters:
7400: # $uri - input URI
7401: # Returns:
7402: # Two element list consisting of
7403: # $pathname - the URI up to and excluding the trailing /
7404: # $filename - The part of the URI following the last /
7405: # NOTE:
7406: # Another realization of this is simply:
7407: # use File::Basename;
7408: # ...
7409: # $uri = shift;
7410: # $filename = basename($uri);
7411: # $path = dirname($uri);
7412: # return ($filename, $path);
7413: #
7414: # The implementation below is probably faster however.
7415: #
1.710 albertel 7416: sub split_uri_for_cond {
7417: my $uri=&deversion(&declutter(shift));
7418: my @uriparts=split(/\//,$uri);
7419: my $filename=pop(@uriparts);
7420: my $pathname=join('/',@uriparts);
7421: return ($pathname,$filename);
7422: }
1.232 www 7423: # --------------------------------------------------- Is a resource on the map?
7424:
7425: sub is_on_map {
1.710 albertel 7426: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7427: #Trying to find the conditional for the file
1.620 albertel 7428: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7429: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7430: if ($match) {
1.289 bowersj2 7431: return (1,$1);
7432: } else {
1.434 www 7433: return (0,0);
1.289 bowersj2 7434: }
1.12 www 7435: }
7436:
1.427 www 7437: # --------------------------------------------------------- Get symb from alias
7438:
7439: sub get_symb_from_alias {
7440: my $symb=shift;
7441: my ($map,$resid,$url)=&decode_symb($symb);
7442: # Already is a symb
7443: if ($url) { return $symb; }
7444: # Must be an alias
7445: my $aliassymb='';
7446: my %bighash;
1.620 albertel 7447: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7448: &GDBM_READER(),0640)) {
7449: my $rid=$bighash{'mapalias_'.$symb};
7450: if ($rid) {
7451: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7452: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7453: $resid,$bighash{'src_'.$rid});
1.427 www 7454: }
7455: untie %bighash;
7456: }
7457: return $aliassymb;
7458: }
7459:
1.12 www 7460: # ----------------------------------------------------------------- Define Role
7461:
7462: sub definerole {
7463: if (allowed('mcr','/')) {
7464: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7465: foreach my $role (split(':',$sysrole)) {
7466: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7467: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7468: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7469: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7470: return "refused:s:$crole&$cqual";
7471: }
7472: }
1.191 harris41 7473: }
1.800 albertel 7474: foreach my $role (split(':',$domrole)) {
7475: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7476: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7477: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7478: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7479: return "refused:d:$crole&$cqual";
7480: }
7481: }
1.191 harris41 7482: }
1.800 albertel 7483: foreach my $role (split(':',$courole)) {
7484: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7485: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7486: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7487: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7488: return "refused:c:$crole&$cqual";
7489: }
7490: }
1.191 harris41 7491: }
1.620 albertel 7492: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7493: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7494: "rolesdef_$rolename=".
7495: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7496: return reply($command,$env{'user.home'});
1.12 www 7497: } else {
7498: return 'refused';
7499: }
1.105 harris41 7500: }
7501:
7502: # ---------------- Make a metadata query against the network of library servers
7503:
7504: sub metadata_query {
1.1172.2.33 raeburn 7505: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7506: my %rhash;
1.845 albertel 7507: my %libserv = &all_library();
1.244 matthew 7508: my @server_list = (defined($server_array) ? @$server_array
7509: : keys(%libserv) );
7510: for my $server (@server_list) {
1.1172.2.33 raeburn 7511: my $domains = '';
7512: if (ref($domains_hash) eq 'HASH') {
7513: $domains = $domains_hash->{$server};
7514: }
1.118 harris41 7515: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7516: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7517: $rhash{$server}=$reply;
7518: }
7519: else {
7520: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7521: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7522: $server);
7523: $rhash{$server}=$reply;
7524: }
1.112 harris41 7525: }
1.118 harris41 7526: return \%rhash;
1.240 www 7527: }
7528:
7529: # ----------------------------------------- Send log queries and wait for reply
7530:
7531: sub log_query {
7532: my ($uname,$udom,$query,%filters)=@_;
7533: my $uhome=&homeserver($uname,$udom);
7534: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7535: my $uhost=&hostname($uhome);
1.800 albertel 7536: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7537: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7538: $uhome);
1.479 albertel 7539: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7540: return get_query_reply($queryid);
7541: }
7542:
1.818 raeburn 7543: # -------------------------- Update MySQL table for portfolio file
7544:
7545: sub update_portfolio_table {
1.821 raeburn 7546: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7547: if ($group ne '') {
7548: $file_name =~s /^\Q$group\E//;
7549: }
1.818 raeburn 7550: my $homeserver = &homeserver($uname,$udom);
7551: my $queryid=
1.821 raeburn 7552: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7553: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7554: my $reply = &get_query_reply($queryid);
7555: return $reply;
7556: }
7557:
1.899 raeburn 7558: # -------------------------- Update MySQL allusers table
7559:
7560: sub update_allusers_table {
7561: my ($uname,$udom,$names) = @_;
7562: my $homeserver = &homeserver($uname,$udom);
7563: my $queryid=
7564: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7565: 'lastname='.&escape($names->{'lastname'}).'%%'.
7566: 'firstname='.&escape($names->{'firstname'}).'%%'.
7567: 'middlename='.&escape($names->{'middlename'}).'%%'.
7568: 'generation='.&escape($names->{'generation'}).'%%'.
7569: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7570: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7571: return;
1.899 raeburn 7572: }
7573:
1.508 raeburn 7574: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7575:
7576: sub fetch_enrollment_query {
1.511 raeburn 7577: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7578: my $homeserver;
1.547 raeburn 7579: my $maxtries = 1;
1.508 raeburn 7580: if ($context eq 'automated') {
7581: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7582: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7583: } else {
7584: $homeserver = &homeserver($cnum,$dom);
7585: }
1.838 albertel 7586: my $host=&hostname($homeserver);
1.506 raeburn 7587: my $cmd = '';
1.1000 raeburn 7588: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7589: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7590: }
7591: $cmd =~ s/%%$//;
7592: $cmd = &escape($cmd);
7593: my $query = 'fetchenrollment';
1.620 albertel 7594: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7595: unless ($queryid=~/^\Q$host\E\_/) {
7596: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7597: return 'error: '.$queryid;
7598: }
1.506 raeburn 7599: my $reply = &get_query_reply($queryid);
1.547 raeburn 7600: my $tries = 1;
7601: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7602: $reply = &get_query_reply($queryid);
7603: $tries ++;
7604: }
1.526 raeburn 7605: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7606: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7607: } else {
1.901 albertel 7608: my @responses = split(/:/,$reply);
1.515 raeburn 7609: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7610: foreach my $line (@responses) {
7611: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7612: $$replyref{$key} = $value;
7613: }
7614: } else {
1.1117 foxr 7615: my $pathname = LONCAPA::tempdir();
1.800 albertel 7616: foreach my $line (@responses) {
7617: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7618: $$replyref{$key} = $value;
7619: if ($value > 0) {
1.800 albertel 7620: foreach my $item (@{$$affiliatesref{$key}}) {
7621: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7622: my $destname = $pathname.'/'.$filename;
7623: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7624: if ($xml_classlist =~ /^error/) {
7625: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7626: } else {
1.506 raeburn 7627: if ( open(FILE,">$destname") ) {
7628: print FILE &unescape($xml_classlist);
7629: close(FILE);
1.526 raeburn 7630: } else {
7631: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7632: }
7633: }
7634: }
7635: }
7636: }
7637: }
7638: return 'ok';
7639: }
7640: return 'error';
7641: }
7642:
1.242 www 7643: sub get_query_reply {
7644: my $queryid=shift;
1.1117 foxr 7645: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7646: my $reply='';
7647: for (1..100) {
7648: sleep 2;
7649: if (-e $replyfile.'.end') {
1.448 albertel 7650: if (open(my $fh,$replyfile)) {
1.904 albertel 7651: $reply = join('',<$fh>);
7652: close($fh);
1.240 www 7653: } else { return 'error: reply_file_error'; }
1.242 www 7654: return &unescape($reply);
7655: }
1.240 www 7656: }
1.242 www 7657: return 'timeout:'.$queryid;
1.240 www 7658: }
7659:
7660: sub courselog_query {
1.241 www 7661: #
7662: # possible filters:
7663: # url: url or symb
7664: # username
7665: # domain
7666: # action: view, submit, grade
7667: # start: timestamp
7668: # end: timestamp
7669: #
1.240 www 7670: my (%filters)=@_;
1.620 albertel 7671: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7672: if ($filters{'url'}) {
7673: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7674: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7675: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7676: }
1.620 albertel 7677: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7678: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7679: return &log_query($cname,$cdom,'courselog',%filters);
7680: }
7681:
7682: sub userlog_query {
1.858 raeburn 7683: #
7684: # possible filters:
7685: # action: log check role
7686: # start: timestamp
7687: # end: timestamp
7688: #
1.240 www 7689: my ($uname,$udom,%filters)=@_;
7690: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7691: }
7692:
1.506 raeburn 7693: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7694:
7695: sub auto_run {
1.508 raeburn 7696: my ($cnum,$cdom) = @_;
1.876 raeburn 7697: my $response = 0;
7698: my $settings;
7699: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7700: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7701: $settings = $domconfig{'autoenroll'};
7702: if ($settings->{'run'} eq '1') {
7703: $response = 1;
7704: }
7705: } else {
1.934 raeburn 7706: my $homeserver;
7707: if (&is_course($cdom,$cnum)) {
7708: $homeserver = &homeserver($cnum,$cdom);
7709: } else {
7710: $homeserver = &domain($cdom,'primary');
7711: }
7712: if ($homeserver ne 'no_host') {
7713: $response = &reply('autorun:'.$cdom,$homeserver);
7714: }
1.876 raeburn 7715: }
1.506 raeburn 7716: return $response;
7717: }
1.776 albertel 7718:
1.506 raeburn 7719: sub auto_get_sections {
1.508 raeburn 7720: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7721: my $homeserver;
7722: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7723: $homeserver = &homeserver($cnum,$cdom);
7724: }
7725: if (!defined($homeserver)) {
7726: if ($cdom =~ /^$match_domain$/) {
7727: $homeserver = &domain($cdom,'primary');
7728: }
7729: }
7730: my @secs;
7731: if (defined($homeserver)) {
7732: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7733: unless ($response eq 'refused') {
7734: @secs = split(/:/,$response);
7735: }
1.506 raeburn 7736: }
7737: return @secs;
7738: }
1.776 albertel 7739:
1.506 raeburn 7740: sub auto_new_course {
1.1099 raeburn 7741: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7742: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7743: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7744: return $response;
7745: }
1.776 albertel 7746:
1.506 raeburn 7747: sub auto_validate_courseID {
1.508 raeburn 7748: my ($cnum,$cdom,$inst_course_id) = @_;
7749: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7750: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7751: return $response;
7752: }
1.776 albertel 7753:
1.1007 raeburn 7754: sub auto_validate_instcode {
1.1020 raeburn 7755: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7756: my ($homeserver,$response);
7757: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7758: $homeserver = &homeserver($cnum,$cdom);
7759: }
7760: if (!defined($homeserver)) {
7761: if ($cdom =~ /^$match_domain$/) {
7762: $homeserver = &domain($cdom,'primary');
7763: }
7764: }
1.1065 raeburn 7765: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7766: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7767: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7768: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7769: }
7770:
1.506 raeburn 7771: sub auto_create_password {
1.873 raeburn 7772: my ($cnum,$cdom,$authparam,$udom) = @_;
7773: my ($homeserver,$response);
1.506 raeburn 7774: my $create_passwd = 0;
7775: my $authchk = '';
1.873 raeburn 7776: if ($udom =~ /^$match_domain$/) {
7777: $homeserver = &domain($udom,'primary');
7778: }
7779: if ($homeserver eq '') {
7780: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7781: $homeserver = &homeserver($cnum,$cdom);
7782: }
7783: }
7784: if ($homeserver eq '') {
7785: $authchk = 'nodomain';
1.506 raeburn 7786: } else {
1.873 raeburn 7787: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7788: if ($response eq 'refused') {
7789: $authchk = 'refused';
7790: } else {
1.901 albertel 7791: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7792: }
1.506 raeburn 7793: }
7794: return ($authparam,$create_passwd,$authchk);
7795: }
7796:
1.706 raeburn 7797: sub auto_photo_permission {
7798: my ($cnum,$cdom,$students) = @_;
7799: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7800: my ($outcome,$perm_reqd,$conditions) =
7801: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7802: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7803: return (undef,undef);
7804: }
1.706 raeburn 7805: return ($outcome,$perm_reqd,$conditions);
7806: }
7807:
7808: sub auto_checkphotos {
7809: my ($uname,$udom,$pid) = @_;
7810: my $homeserver = &homeserver($uname,$udom);
7811: my ($result,$resulttype);
7812: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7813: &escape($uname).':'.&escape($pid),
7814: $homeserver));
1.709 albertel 7815: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7816: return (undef,undef);
7817: }
1.706 raeburn 7818: if ($outcome) {
7819: ($result,$resulttype) = split(/:/,$outcome);
7820: }
7821: return ($result,$resulttype);
7822: }
7823:
7824: sub auto_photochoice {
7825: my ($cnum,$cdom) = @_;
7826: my $homeserver = &homeserver($cnum,$cdom);
7827: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7828: &escape($cdom),
7829: $homeserver)));
1.709 albertel 7830: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7831: return (undef,undef);
7832: }
1.706 raeburn 7833: return ($update,$comment);
7834: }
7835:
7836: sub auto_photoupdate {
7837: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7838: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7839: my $host=&hostname($homeserver);
1.706 raeburn 7840: my $cmd = '';
7841: my $maxtries = 1;
1.800 albertel 7842: foreach my $affiliate (keys(%{$affiliatesref})) {
7843: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7844: }
7845: $cmd =~ s/%%$//;
7846: $cmd = &escape($cmd);
7847: my $query = 'institutionalphotos';
7848: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7849: unless ($queryid=~/^\Q$host\E\_/) {
7850: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7851: return 'error: '.$queryid;
7852: }
7853: my $reply = &get_query_reply($queryid);
7854: my $tries = 1;
7855: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7856: $reply = &get_query_reply($queryid);
7857: $tries ++;
7858: }
7859: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7860: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7861: } else {
7862: my @responses = split(/:/,$reply);
7863: my $outcome = shift(@responses);
7864: foreach my $item (@responses) {
7865: my ($key,$value) = split(/=/,$item);
7866: $$photo{$key} = $value;
7867: }
7868: return $outcome;
7869: }
7870: return 'error';
7871: }
7872:
1.521 raeburn 7873: sub auto_instcode_format {
1.793 albertel 7874: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7875: $cat_order) = @_;
1.521 raeburn 7876: my $courses = '';
1.772 raeburn 7877: my @homeservers;
1.521 raeburn 7878: if ($caller eq 'global') {
1.841 albertel 7879: my %servers = &get_servers($codedom,'library');
7880: foreach my $tryserver (keys(%servers)) {
7881: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7882: push(@homeservers,$tryserver);
7883: }
1.584 raeburn 7884: }
1.1022 raeburn 7885: } elsif ($caller eq 'requests') {
7886: if ($codedom =~ /^$match_domain$/) {
7887: my $chome = &domain($codedom,'primary');
7888: unless ($chome eq 'no_host') {
7889: push(@homeservers,$chome);
7890: }
7891: }
1.521 raeburn 7892: } else {
1.772 raeburn 7893: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7894: }
1.793 albertel 7895: foreach my $code (keys(%{$instcodes})) {
7896: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7897: }
7898: chop($courses);
1.772 raeburn 7899: my $ok_response = 0;
7900: my $response;
7901: while (@homeservers > 0 && $ok_response == 0) {
7902: my $server = shift(@homeservers);
7903: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7904: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7905: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7906: split(/:/,$response);
1.772 raeburn 7907: %{$codes} = (%{$codes},&str2hash($codes_str));
7908: push(@{$codetitles},&str2array($codetitles_str));
7909: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7910: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7911: $ok_response = 1;
7912: }
7913: }
7914: if ($ok_response) {
1.521 raeburn 7915: return 'ok';
1.772 raeburn 7916: } else {
7917: return $response;
1.521 raeburn 7918: }
7919: }
7920:
1.792 raeburn 7921: sub auto_instcode_defaults {
7922: my ($domain,$returnhash,$code_order) = @_;
7923: my @homeservers;
1.841 albertel 7924:
7925: my %servers = &get_servers($domain,'library');
7926: foreach my $tryserver (keys(%servers)) {
7927: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7928: push(@homeservers,$tryserver);
7929: }
1.792 raeburn 7930: }
1.841 albertel 7931:
1.792 raeburn 7932: my $response;
1.841 albertel 7933: foreach my $server (@homeservers) {
1.792 raeburn 7934: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7935: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7936:
7937: foreach my $pair (split(/\&/,$response)) {
7938: my ($name,$value)=split(/\=/,$pair);
7939: if ($name eq 'code_order') {
7940: @{$code_order} = split(/\&/,&unescape($value));
7941: } else {
7942: $returnhash->{&unescape($name)}=&unescape($value);
7943: }
7944: }
7945: return 'ok';
1.792 raeburn 7946: }
1.841 albertel 7947:
7948: return $response;
1.1003 raeburn 7949: }
7950:
7951: sub auto_possible_instcodes {
1.1007 raeburn 7952: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7953: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7954: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7955: return;
7956: }
1.1003 raeburn 7957: my (@homeservers,$uhome);
7958: if (defined(&domain($domain,'primary'))) {
7959: $uhome=&domain($domain,'primary');
7960: push(@homeservers,&domain($domain,'primary'));
7961: } else {
7962: my %servers = &get_servers($domain,'library');
7963: foreach my $tryserver (keys(%servers)) {
7964: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7965: push(@homeservers,$tryserver);
7966: }
7967: }
7968: }
7969: my $response;
7970: foreach my $server (@homeservers) {
7971: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7972: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7973: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7974: split(':',$response);
7975: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7976: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7977: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7978: my ($name,$value)=split('=',$item);
7979: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7980: }
7981: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7982: my ($name,$value)=split('=',$item);
7983: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7984: }
7985: return 'ok';
7986: }
7987: return $response;
7988: }
1.792 raeburn 7989:
1.1010 raeburn 7990: sub auto_courserequest_checks {
7991: my ($dom) = @_;
1.1020 raeburn 7992: my ($homeserver,%validations);
7993: if ($dom =~ /^$match_domain$/) {
7994: $homeserver = &domain($dom,'primary');
7995: }
7996: unless ($homeserver eq 'no_host') {
7997: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7998: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7999: my @items = split(/&/,$response);
8000: foreach my $item (@items) {
8001: my ($key,$value) = split('=',$item);
8002: $validations{&unescape($key)} = &thaw_unescape($value);
8003: }
8004: }
8005: }
1.1010 raeburn 8006: return %validations;
8007: }
8008:
1.1020 raeburn 8009: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8010: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8011: my ($homeserver,$response);
8012: if ($dom =~ /^$match_domain$/) {
8013: $homeserver = &domain($dom,'primary');
8014: }
1.1172.2.43 raeburn 8015: unless ($homeserver eq 'no_host') {
8016: my $customdata;
8017: if (ref($custominfo) eq 'HASH') {
8018: $customdata = &freeze_escape($custominfo);
8019: }
1.1020 raeburn 8020: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8021: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8022: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8023: $customdata,$homeserver));
1.1020 raeburn 8024: }
8025: return $response;
8026: }
8027:
1.777 albertel 8028: sub auto_validate_class_sec {
1.918 raeburn 8029: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8030: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8031: my $ownerlist;
8032: if (ref($owners) eq 'ARRAY') {
8033: $ownerlist = join(',',@{$owners});
8034: } else {
8035: $ownerlist = $owners;
8036: }
1.773 raeburn 8037: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8038: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8039: return $response;
8040: }
8041:
1.1172.2.38 raeburn 8042: sub auto_crsreq_update {
8043: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8044: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8045: my ($homeserver,%crsreqresponse);
8046: if ($cdom =~ /^$match_domain$/) {
8047: $homeserver = &domain($cdom,'primary');
8048: }
8049: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8050: my $info;
8051: if (ref($inbound) eq 'HASH') {
8052: $info = &freeze_escape($inbound);
8053: }
8054: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8055: ':'.&escape($action).':'.&escape($ownername).':'.
8056: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8057: &escape($title).':'.&escape($code).':'.
8058: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8059: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8060: my @items = split(/&/,$response);
8061: foreach my $item (@items) {
8062: my ($key,$value) = split('=',$item);
8063: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8064: }
8065: }
8066: }
8067: return \%crsreqresponse;
8068: }
8069:
1.679 raeburn 8070: # ------------------------------------------------------- Course Group routines
8071:
8072: sub get_coursegroups {
1.809 raeburn 8073: my ($cdom,$cnum,$group,$namespace) = @_;
8074: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8075: }
8076:
1.679 raeburn 8077: sub modify_coursegroup {
8078: my ($cdom,$cnum,$groupsettings) = @_;
8079: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8080: }
8081:
1.809 raeburn 8082: sub toggle_coursegroup_status {
8083: my ($cdom,$cnum,$group,$action) = @_;
8084: my ($from_namespace,$to_namespace);
8085: if ($action eq 'delete') {
8086: $from_namespace = 'coursegroups';
8087: $to_namespace = 'deleted_groups';
8088: } else {
8089: $from_namespace = 'deleted_groups';
8090: $to_namespace = 'coursegroups';
8091: }
8092: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8093: if (my $tmp = &error(%curr_group)) {
8094: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8095: return ('read error',$tmp);
8096: } else {
8097: my %savedsettings = %curr_group;
1.809 raeburn 8098: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8099: my $deloutcome;
8100: if ($result eq 'ok') {
1.809 raeburn 8101: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8102: } else {
8103: return ('write error',$result);
8104: }
8105: if ($deloutcome eq 'ok') {
8106: return 'ok';
8107: } else {
8108: return ('delete error',$deloutcome);
8109: }
8110: }
8111: }
8112:
1.679 raeburn 8113: sub modify_group_roles {
1.957 raeburn 8114: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8115: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8116: my $role = 'gr/'.&escape($userprivs);
8117: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8118: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8119: if ($result eq 'ok') {
8120: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8121: }
1.679 raeburn 8122: return $result;
8123: }
8124:
8125: sub modify_coursegroup_membership {
8126: my ($cdom,$cnum,$membership) = @_;
8127: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8128: return $result;
8129: }
8130:
1.682 raeburn 8131: sub get_active_groups {
8132: my ($udom,$uname,$cdom,$cnum) = @_;
8133: my $now = time;
8134: my %groups = ();
8135: foreach my $key (keys(%env)) {
1.811 albertel 8136: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8137: my ($start,$end) = split(/\./,$env{$key});
8138: if (($end!=0) && ($end<$now)) { next; }
8139: if (($start!=0) && ($start>$now)) { next; }
8140: if ($1 eq $cdom && $2 eq $cnum) {
8141: $groups{$3} = $env{$key} ;
8142: }
8143: }
8144: }
8145: return %groups;
8146: }
8147:
1.683 raeburn 8148: sub get_group_membership {
8149: my ($cdom,$cnum,$group) = @_;
8150: return(&dump('groupmembership',$cdom,$cnum,$group));
8151: }
8152:
8153: sub get_users_groups {
8154: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8155: my @usersgroups;
1.683 raeburn 8156: my $cachetime=1800;
8157:
8158: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8159: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8160: if (defined($cached)) {
1.734 albertel 8161: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8162: } else {
8163: $grouplist = '';
1.816 raeburn 8164: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8165: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8166: my $access_end = $env{'course.'.$courseid.
8167: '.default_enrollment_end_date'};
8168: my $now = time;
8169: foreach my $key (keys(%roleshash)) {
8170: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8171: my $group = $1;
8172: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8173: my $start = $2;
8174: my $end = $1;
8175: if ($start == -1) { next; } # deleted from group
8176: if (($start!=0) && ($start>$now)) { next; }
8177: if (($end!=0) && ($end<$now)) {
8178: if ($access_end && $access_end < $now) {
8179: if ($access_end - $end < 86400) {
8180: push(@usersgroups,$group);
1.733 raeburn 8181: }
8182: }
1.817 raeburn 8183: next;
1.733 raeburn 8184: }
1.817 raeburn 8185: push(@usersgroups,$group);
1.683 raeburn 8186: }
8187: }
8188: }
1.817 raeburn 8189: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8190: $grouplist = join(':',@usersgroups);
8191: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8192: }
1.733 raeburn 8193: return @usersgroups;
1.683 raeburn 8194: }
8195:
8196: sub devalidate_getgroups_cache {
8197: my ($udom,$uname,$cdom,$cnum)=@_;
8198: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8199:
1.683 raeburn 8200: my $hashid="$udom:$uname:$courseid";
8201: &devalidate_cache_new('getgroups',$hashid);
8202: }
8203:
1.12 www 8204: # ------------------------------------------------------------------ Plain Text
8205:
8206: sub plaintext {
1.988 raeburn 8207: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8208: if ($short =~ m{^cr/}) {
1.758 albertel 8209: return (split('/',$short))[-1];
8210: }
1.742 raeburn 8211: if (!defined($cid)) {
8212: $cid = $env{'request.course.id'};
8213: }
8214: my %rolenames = (
1.1008 raeburn 8215: Course => 'std',
8216: Community => 'alt1',
1.742 raeburn 8217: );
1.1037 raeburn 8218: if ($cid ne '') {
8219: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8220: unless ($forcedefault) {
8221: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8222: &Apache::lonlocal::mt_escape(\$roletext);
8223: return &Apache::lonlocal::mt($roletext);
8224: }
8225: }
8226: }
8227: if ((defined($type)) && (defined($rolenames{$type})) &&
8228: (defined($rolenames{$type})) &&
8229: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8230: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8231: } elsif ($cid ne '') {
8232: my $crstype = $env{'course.'.$cid.'.type'};
8233: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8234: (defined($prp{$short}{$rolenames{$crstype}}))) {
8235: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8236: }
1.742 raeburn 8237: }
1.1037 raeburn 8238: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8239: }
8240:
8241: # ----------------------------------------------------------------- Assign Role
8242:
8243: sub assignrole {
1.957 raeburn 8244: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8245: $context)=@_;
1.21 www 8246: my $mrole;
8247: if ($role =~ /^cr\//) {
1.393 www 8248: my $cwosec=$url;
1.811 albertel 8249: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8250: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8251: my $refused = 1;
8252: if ($context eq 'requestcourses') {
8253: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8254: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8255: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8256: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8257: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8258: if ($crsenv{'internal.courseowner'} eq
8259: $env{'user.name'}.':'.$env{'user.domain'}) {
8260: $refused = '';
8261: }
8262: }
8263: }
8264: }
8265: }
8266: if ($refused) {
8267: &logthis('Refused custom assignrole: '.
8268: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8269: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8270: return 'refused';
8271: }
1.104 www 8272: }
1.21 www 8273: $mrole='cr';
1.678 raeburn 8274: } elsif ($role =~ /^gr\//) {
8275: my $cwogrp=$url;
1.811 albertel 8276: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8277: unless (&allowed('mdg',$cwogrp)) {
8278: &logthis('Refused group assignrole: '.
8279: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8280: $env{'user.name'}.' at '.$env{'user.domain'});
8281: return 'refused';
8282: }
8283: $mrole='gr';
1.21 www 8284: } else {
1.82 www 8285: my $cwosec=$url;
1.811 albertel 8286: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8287: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8288: my $refused;
8289: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8290: if (!(&allowed('c'.$role,$url))) {
8291: $refused = 1;
8292: }
8293: } else {
8294: $refused = 1;
8295: }
1.947 raeburn 8296: if ($refused) {
1.1045 raeburn 8297: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8298: if (!$selfenroll && $context eq 'course') {
8299: my %crsenv;
8300: if ($role eq 'cc' || $role eq 'co') {
8301: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8302: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8303: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8304: if ($crsenv{'internal.courseowner'} eq
8305: $env{'user.name'}.':'.$env{'user.domain'}) {
8306: $refused = '';
8307: }
8308: }
8309: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8310: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8311: if ($crsenv{'internal.courseowner'} eq
8312: $env{'user.name'}.':'.$env{'user.domain'}) {
8313: $refused = '';
8314: }
8315: }
8316: }
8317: }
8318: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8319: $refused = '';
1.1017 raeburn 8320: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8321: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8322: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8323: my $wrongcc;
8324: if ($cnum =~ /^$match_community$/) {
8325: $wrongcc = 1 if ($role eq 'cc');
8326: } else {
8327: $wrongcc = 1 if ($role eq 'co');
8328: }
8329: unless ($wrongcc) {
8330: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8331: if ($crsenv{'internal.courseowner'} eq
8332: $env{'user.name'}.':'.$env{'user.domain'}) {
8333: $refused = '';
8334: }
1.1017 raeburn 8335: }
8336: }
1.1172.2.9 raeburn 8337: } elsif ($context eq 'requestauthor') {
8338: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8339: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8340: if ($env{'environment.requestauthor'} eq 'automatic') {
8341: $refused = '';
8342: } else {
8343: my %domdefaults = &get_domain_defaults($udom);
8344: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8345: my $checkbystatus;
8346: if ($env{'user.adv'}) {
8347: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8348: if ($disposition eq 'automatic') {
8349: $refused = '';
8350: } elsif ($disposition eq '') {
8351: $checkbystatus = 1;
8352: }
8353: } else {
8354: $checkbystatus = 1;
8355: }
8356: if ($checkbystatus) {
8357: if ($env{'environment.inststatus'}) {
8358: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8359: foreach my $type (@inststatuses) {
8360: if (($type ne '') &&
8361: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8362: $refused = '';
8363: }
8364: }
8365: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8366: $refused = '';
8367: }
8368: }
8369: }
8370: }
8371: }
1.1017 raeburn 8372: }
8373: if ($refused) {
1.947 raeburn 8374: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8375: ' '.$role.' '.$end.' '.$start.' by '.
8376: $env{'user.name'}.' at '.$env{'user.domain'});
8377: return 'refused';
8378: }
1.932 raeburn 8379: }
1.1131 raeburn 8380: } elsif ($role eq 'au') {
8381: if ($url ne '/'.$udom.'/') {
8382: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8383: ' to assign author role for '.$uname.':'.$udom.
8384: ' in domain: '.$url.' refused (wrong domain).');
8385: return 'refused';
8386: }
1.104 www 8387: }
1.21 www 8388: $mrole=$role;
8389: }
1.620 albertel 8390: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8391: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8392: if ($end) { $command.='_'.$end; }
1.21 www 8393: if ($start) {
8394: if ($end) {
1.81 www 8395: $command.='_'.$start;
1.21 www 8396: } else {
1.81 www 8397: $command.='_0_'.$start;
1.21 www 8398: }
8399: }
1.739 raeburn 8400: my $origstart = $start;
8401: my $origend = $end;
1.957 raeburn 8402: my $delflag;
1.357 www 8403: # actually delete
8404: if ($deleteflag) {
1.373 www 8405: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8406: # modify command to delete the role
1.620 albertel 8407: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8408: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8409: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8410: # set start and finish to negative values for userrolelog
8411: $start=-1;
8412: $end=-1;
1.957 raeburn 8413: $delflag = 1;
1.357 www 8414: }
8415: }
8416: # send command
1.349 www 8417: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8418: # log new user role if status is ok
1.349 www 8419: if ($answer eq 'ok') {
1.663 raeburn 8420: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8421: if (($role eq 'cc') || ($role eq 'in') ||
8422: ($role eq 'ep') || ($role eq 'ad') ||
8423: ($role eq 'ta') || ($role eq 'st') ||
8424: ($role=~/^cr/) || ($role eq 'gr') ||
8425: ($role eq 'co')) {
1.1172.2.13 raeburn 8426: # for course roles, perform group memberships changes triggered by role change.
8427: unless ($role =~ /^gr/) {
8428: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8429: $origstart,$selfenroll,$context);
8430: }
1.1172.2.9 raeburn 8431: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8432: $selfenroll,$context);
8433: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8434: ($role eq 'au') || ($role eq 'dc')) {
8435: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8436: $context);
8437: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8438: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8439: $context);
8440: }
1.1053 raeburn 8441: if ($role eq 'cc') {
8442: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8443: }
1.349 www 8444: }
8445: return $answer;
1.169 harris41 8446: }
8447:
1.1053 raeburn 8448: sub autoupdate_coowners {
8449: my ($url,$end,$start,$uname,$udom) = @_;
8450: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8451: if (($cdom ne '') && ($cnum ne '')) {
8452: my $now = time;
8453: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8454: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8455: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8456: my $instcode = $coursehash{'internal.coursecode'};
8457: if ($instcode ne '') {
1.1056 raeburn 8458: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8459: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8460: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8461: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8462: if ($result eq 'valid') {
8463: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8464: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8465: push(@newcoowners,$coowner);
8466: }
8467: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8468: push(@newcoowners,$uname.':'.$udom);
8469: }
8470: @newcoowners = sort(@newcoowners);
8471: } else {
8472: push(@newcoowners,$uname.':'.$udom);
8473: }
8474: } else {
8475: if ($coursehash{'internal.co-owners'}) {
8476: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8477: unless ($coowner eq $uname.':'.$udom) {
8478: push(@newcoowners,$coowner);
8479: }
8480: }
8481: unless (@newcoowners > 0) {
8482: $delcoowners = 1;
8483: $coowners = '';
8484: }
8485: }
8486: }
8487: if (@newcoowners || $delcoowners) {
8488: &store_coowners($cdom,$cnum,$coursehash{'home'},
8489: $delcoowners,@newcoowners);
8490: }
8491: }
8492: }
8493: }
8494: }
8495: }
8496: }
8497:
8498: sub store_coowners {
8499: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8500: my $cid = $cdom.'_'.$cnum;
8501: my ($coowners,$delresult,$putresult);
8502: if (@newcoowners) {
8503: $coowners = join(',',@newcoowners);
8504: my %coownershash = (
8505: 'internal.co-owners' => $coowners,
8506: );
8507: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8508: if ($putresult eq 'ok') {
8509: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8510: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8511: }
8512: }
8513: }
8514: if ($delcoowners) {
8515: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8516: if ($delresult eq 'ok') {
8517: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8518: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8519: }
8520: }
8521: }
8522: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8523: my %crsinfo =
8524: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8525: if (ref($crsinfo{$cid}) eq 'HASH') {
8526: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8527: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8528: }
8529: }
8530: }
8531:
1.169 harris41 8532: # -------------------------------------------------- Modify user authentication
1.197 www 8533: # Overrides without validation
8534:
1.169 harris41 8535: sub modifyuserauth {
8536: my ($udom,$uname,$umode,$upass)=@_;
8537: my $uhome=&homeserver($uname,$udom);
1.197 www 8538: unless (&allowed('mau',$udom)) { return 'refused'; }
8539: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8540: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8541: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8542: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8543: &escape($upass),$uhome);
1.620 albertel 8544: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8545: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8546: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8547: &log($udom,,$uname,$uhome,
1.620 albertel 8548: 'Authentication changed by '.$env{'user.domain'}.', '.
8549: $env{'user.name'}.', '.$umode.
1.197 www 8550: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8551: unless ($reply eq 'ok') {
1.197 www 8552: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8553: return 'error: '.$reply;
8554: }
1.170 harris41 8555: return 'ok';
1.80 www 8556: }
8557:
1.81 www 8558: # --------------------------------------------------------------- Modify a user
1.80 www 8559:
1.81 www 8560: sub modifyuser {
1.206 matthew 8561: my ($udom, $uname, $uid,
8562: $umode, $upass, $first,
8563: $middle, $last, $gene,
1.1058 raeburn 8564: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8565: $udom= &LONCAPA::clean_domain($udom);
8566: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8567: my $showcandelete = 'none';
8568: if (ref($candelete) eq 'ARRAY') {
8569: if (@{$candelete} > 0) {
8570: $showcandelete = join(', ',@{$candelete});
8571: }
8572: }
1.81 www 8573: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8574: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8575: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8576: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8577: ' desiredhome not specified').
1.620 albertel 8578: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8579: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8580: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8581: my $newuser;
8582: if ($uhome eq 'no_host') {
8583: $newuser = 1;
8584: }
1.80 www 8585: # ----------------------------------------------------------------- Create User
1.406 albertel 8586: if (($uhome eq 'no_host') &&
8587: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8588: my $unhome='';
1.844 albertel 8589: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8590: $unhome = $desiredhome;
1.620 albertel 8591: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8592: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8593: } else { # load balancing routine for determining $unhome
1.81 www 8594: my $loadm=10000000;
1.841 albertel 8595: my %servers = &get_servers($udom,'library');
8596: foreach my $tryserver (keys(%servers)) {
8597: my $answer=reply('load',$tryserver);
8598: if (($answer=~/\d+/) && ($answer<$loadm)) {
8599: $loadm=$answer;
8600: $unhome=$tryserver;
8601: }
1.80 www 8602: }
8603: }
8604: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8605: return 'error: unable to find a home server for '.$uname.
8606: ' in domain '.$udom;
1.80 www 8607: }
8608: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8609: &escape($upass),$unhome);
8610: unless ($reply eq 'ok') {
8611: return 'error: '.$reply;
8612: }
1.230 stredwic 8613: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8614: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8615: return 'error: unable verify users home machine.';
1.80 www 8616: }
1.209 matthew 8617: } # End of creation of new user
1.80 www 8618: # ---------------------------------------------------------------------- Add ID
8619: if ($uid) {
8620: $uid=~tr/A-Z/a-z/;
8621: my %uidhash=&idrget($udom,$uname);
1.196 www 8622: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8623: && (!$forceid)) {
1.80 www 8624: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8625: return 'error: user id "'.$uid.'" does not match '.
8626: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8627: }
8628: } else {
8629: &idput($udom,($uname => $uid));
8630: }
8631: }
8632: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8633: my @tmp=&get('environment',
1.899 raeburn 8634: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8635: 'permanentemail','inststatus'],
1.134 albertel 8636: $udom,$uname);
1.1075 raeburn 8637: my (%names,%oldnames);
1.313 matthew 8638: if ($tmp[0] =~ m/^error:.*/) {
8639: %names=();
8640: } else {
8641: %names = @tmp;
1.1075 raeburn 8642: %oldnames = %names;
1.313 matthew 8643: }
1.388 www 8644: #
1.1058 raeburn 8645: # If name, email and/or uid are blank (e.g., because an uploaded file
8646: # of users did not contain them), do not overwrite existing values
8647: # unless field is in $candelete array ref.
8648: #
8649:
8650: my @fields = ('firstname','middlename','lastname','generation',
8651: 'permanentemail','id');
8652: my %newvalues;
8653: if (ref($candelete) eq 'ARRAY') {
8654: foreach my $field (@fields) {
8655: if (grep(/^\Q$field\E$/,@{$candelete})) {
8656: if ($field eq 'firstname') {
8657: $names{$field} = $first;
8658: } elsif ($field eq 'middlename') {
8659: $names{$field} = $middle;
8660: } elsif ($field eq 'lastname') {
8661: $names{$field} = $last;
8662: } elsif ($field eq 'generation') {
8663: $names{$field} = $gene;
8664: } elsif ($field eq 'permanentemail') {
8665: $names{$field} = $email;
8666: } elsif ($field eq 'id') {
8667: $names{$field} = $uid;
8668: }
8669: }
8670: }
8671: }
1.388 www 8672: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8673: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8674: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8675: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8676: if ($email) {
8677: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8678: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8679: }
1.899 raeburn 8680: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8681: if (defined($inststatus)) {
8682: $names{'inststatus'} = '';
8683: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8684: if (ref($usertypes) eq 'HASH') {
8685: my @okstatuses;
8686: foreach my $item (split(/:/,$inststatus)) {
8687: if (defined($usertypes->{$item})) {
8688: push(@okstatuses,$item);
8689: }
8690: }
8691: if (@okstatuses) {
8692: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8693: }
8694: }
8695: }
1.1075 raeburn 8696: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8697: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8698: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8699: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8700: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8701: } else {
8702: $logmsg .= ' during self creation';
8703: }
1.1075 raeburn 8704: my $changed;
8705: if ($newuser) {
8706: $changed = 1;
8707: } else {
8708: foreach my $field (@fields) {
8709: if ($names{$field} ne $oldnames{$field}) {
8710: $changed = 1;
8711: last;
8712: }
8713: }
8714: }
8715: unless ($changed) {
8716: $logmsg = 'No changes in user information needed for: '.$logmsg;
8717: &logthis($logmsg);
8718: return 'ok';
8719: }
8720: my $reply = &put('environment', \%names, $udom,$uname);
8721: if ($reply ne 'ok') {
8722: return 'error: '.$reply;
8723: }
1.1087 raeburn 8724: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8725: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8726: }
1.1075 raeburn 8727: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8728: &devalidate_cache_new('namescache',$uname.':'.$udom);
8729: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8730: &logthis($logmsg);
1.134 albertel 8731: return 'ok';
1.80 www 8732: }
8733:
1.81 www 8734: # -------------------------------------------------------------- Modify student
1.80 www 8735:
1.81 www 8736: sub modifystudent {
8737: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8738: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8739: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8740: if (!$cid) {
1.620 albertel 8741: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8742: return 'not_in_class';
8743: }
1.80 www 8744: }
8745: # --------------------------------------------------------------- Make the user
1.81 www 8746: my $reply=&modifyuser
1.209 matthew 8747: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8748: $desiredhome,$email,$inststatus);
1.80 www 8749: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8750: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8751: # student's environment
1.297 matthew 8752: $uid = undef if (!$forceid);
1.455 albertel 8753: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8754: $gene,$usec,$end,$start,$type,$locktype,
8755: $cid,$selfenroll,$context,$credits);
1.297 matthew 8756: return $reply;
8757: }
8758:
8759: sub modify_student_enrollment {
1.1172.2.23 raeburn 8760: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8761: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8762: my ($cdom,$cnum,$chome);
8763: if (!$cid) {
1.620 albertel 8764: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8765: return 'not_in_class';
8766: }
1.620 albertel 8767: $cdom=$env{'course.'.$cid.'.domain'};
8768: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8769: } else {
8770: ($cdom,$cnum)=split(/_/,$cid);
8771: }
1.620 albertel 8772: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8773: if (!$chome) {
1.457 raeburn 8774: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8775: }
1.455 albertel 8776: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8777: # Make sure the user exists
1.81 www 8778: my $uhome=&homeserver($uname,$udom);
8779: if (($uhome eq '') || ($uhome eq 'no_host')) {
8780: return 'error: no such user';
8781: }
1.297 matthew 8782: # Get student data if we were not given enough information
8783: if (!defined($first) || $first eq '' ||
8784: !defined($last) || $last eq '' ||
8785: !defined($uid) || $uid eq '' ||
8786: !defined($middle) || $middle eq '' ||
8787: !defined($gene) || $gene eq '') {
1.294 matthew 8788: # They did not supply us with enough data to enroll the student, so
8789: # we need to pick up more information.
1.297 matthew 8790: my %tmp = &get('environment',
1.294 matthew 8791: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8792: ,$udom,$uname);
8793:
1.800 albertel 8794: #foreach my $key (keys(%tmp)) {
8795: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8796: #}
1.294 matthew 8797: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8798: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8799: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8800: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8801: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8802: }
1.556 albertel 8803: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8804: my $user = "$uname:$udom";
8805: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8806: my $reply=cput('classlist',
1.1148 raeburn 8807: {$user =>
1.1172.2.19 raeburn 8808: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8809: $cdom,$cnum);
1.1148 raeburn 8810: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8811: &devalidate_getsection_cache($udom,$uname,$cid);
8812: } else {
1.81 www 8813: return 'error: '.$reply;
8814: }
1.297 matthew 8815: # Add student role to user
1.83 www 8816: my $uurl='/'.$cid;
1.81 www 8817: $uurl=~s/\_/\//g;
8818: if ($usec) {
8819: $uurl.='/'.$usec;
8820: }
1.1148 raeburn 8821: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8822: $selfenroll,$context);
8823: if ($result ne 'ok') {
8824: if ($old_entry{$user} ne '') {
8825: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8826: } else {
8827: $reply = &del('classlist',[$user],$cdom,$cnum);
8828: }
8829: }
8830: return $result;
1.21 www 8831: }
8832:
1.556 albertel 8833: sub format_name {
8834: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8835: my $name;
8836: if ($first ne 'lastname') {
8837: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8838: } else {
8839: if ($lastname=~/\S/) {
8840: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8841: $name=~s/\s+,/,/;
8842: } else {
8843: $name.= $firstname.' '.$middlename.' '.$generation;
8844: }
8845: }
8846: $name=~s/^\s+//;
8847: $name=~s/\s+$//;
8848: $name=~s/\s+/ /g;
8849: return $name;
8850: }
8851:
1.84 www 8852: # ------------------------------------------------- Write to course preferences
8853:
8854: sub writecoursepref {
8855: my ($courseid,%prefs)=@_;
8856: $courseid=~s/^\///;
8857: $courseid=~s/\_/\//g;
8858: my ($cdomain,$cnum)=split(/\//,$courseid);
8859: my $chome=homeserver($cnum,$cdomain);
8860: if (($chome eq '') || ($chome eq 'no_host')) {
8861: return 'error: no such course';
8862: }
8863: my $cstring='';
1.800 albertel 8864: foreach my $pref (keys(%prefs)) {
8865: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8866: }
1.84 www 8867: $cstring=~s/\&$//;
8868: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8869: }
8870:
8871: # ---------------------------------------------------------- Make/modify course
8872:
8873: sub createcourse {
1.741 raeburn 8874: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8875: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8876: $url=&declutter($url);
8877: my $cid='';
1.1028 raeburn 8878: if ($context eq 'requestcourses') {
8879: my $can_create = 0;
8880: my ($ownername,$ownerdom) = split(':',$course_owner);
8881: if ($udom eq $ownerdom) {
8882: if (&usertools_access($ownername,$ownerdom,$category,undef,
8883: $context)) {
8884: $can_create = 1;
8885: }
8886: } else {
8887: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8888: $category);
8889: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8890: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8891: if (@curr > 0) {
8892: my @options = qw(approval validate autolimit);
8893: my $optregex = join('|',@options);
8894: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8895: $can_create = 1;
8896: }
8897: }
8898: }
8899: }
8900: if ($can_create) {
8901: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8902: unless (&allowed('ccc',$udom)) {
8903: return 'refused';
8904: }
1.1017 raeburn 8905: }
8906: } else {
8907: return 'refused';
8908: }
1.1028 raeburn 8909: } elsif (!&allowed('ccc',$udom)) {
8910: return 'refused';
1.84 www 8911: }
1.1011 raeburn 8912: # --------------------------------------------------------------- Get Unique ID
8913: my $uname;
8914: if ($cnum =~ /^$match_courseid$/) {
8915: my $chome=&homeserver($cnum,$udom,'true');
8916: if (($chome eq '') || ($chome eq 'no_host')) {
8917: $uname = $cnum;
8918: } else {
1.1038 raeburn 8919: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8920: }
8921: } else {
1.1038 raeburn 8922: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8923: }
8924: return $uname if ($uname =~ /^error/);
8925: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8926: if (!defined($course_server)) {
8927: if (defined(&domain($udom,'primary'))) {
8928: $course_server = &domain($udom,'primary');
8929: } else {
8930: $course_server = $env{'user.home'};
8931: }
8932: }
8933: my %host_servers =
8934: &Apache::lonnet::get_servers($udom,'library');
8935: unless ($host_servers{$course_server}) {
8936: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8937: }
1.84 www 8938: # ------------------------------------------------------------- Make the course
8939: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8940: $course_server);
1.84 www 8941: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8942: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8943: if (($uhome eq '') || ($uhome eq 'no_host')) {
8944: return 'error: no such course';
8945: }
1.271 www 8946: # ----------------------------------------------------------------- Course made
1.516 raeburn 8947: # log existence
1.1029 raeburn 8948: my $now = time;
1.918 raeburn 8949: my $newcourse = {
8950: $udom.'_'.$uname => {
1.921 raeburn 8951: description => $description,
8952: inst_code => $inst_code,
8953: owner => $course_owner,
8954: type => $crstype,
1.1029 raeburn 8955: creator => $env{'user.name'}.':'.
8956: $env{'user.domain'},
8957: created => $now,
8958: context => $context,
1.918 raeburn 8959: },
8960: };
1.921 raeburn 8961: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8962: # set toplevel url
1.271 www 8963: my $topurl=$url;
8964: unless ($nonstandard) {
8965: # ------------------------------------------ For standard courses, make top url
8966: my $mapurl=&clutter($url);
1.278 www 8967: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8968: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8969: <map>
8970: <resource id="1" type="start"></resource>
8971: <resource id="2" src="$mapurl"></resource>
8972: <resource id="3" type="finish"></resource>
8973: <link index="1" from="1" to="2"></link>
8974: <link index="2" from="2" to="3"></link>
8975: </map>
8976: ENDINITMAP
8977: $topurl=&declutter(
1.638 albertel 8978: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8979: );
8980: }
8981: # ----------------------------------------------------------- Write preferences
1.84 www 8982: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8983: ('description' => $description,
8984: 'url' => $topurl,
8985: 'internal.creator' => $env{'user.name'}.':'.
8986: $env{'user.domain'},
8987: 'internal.created' => $now,
8988: 'internal.creationcontext' => $context)
8989: );
1.84 www 8990: return '/'.$udom.'/'.$uname;
8991: }
8992:
1.1011 raeburn 8993: # ------------------------------------------------------------------- Create ID
8994: sub generate_coursenum {
1.1038 raeburn 8995: my ($udom,$crstype) = @_;
1.1011 raeburn 8996: my $domdesc = &domain($udom);
8997: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8998: my $first;
8999: if ($crstype eq 'Community') {
9000: $first = '0';
9001: } else {
9002: $first = int(1+rand(9));
9003: }
9004: my $uname=$first.
1.1011 raeburn 9005: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9006: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9007: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9008: # ----------------------------------------------- Make sure that does not exist
9009: my $uhome=&homeserver($uname,$udom,'true');
9010: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9011: if ($crstype eq 'Community') {
9012: $first = '0';
9013: } else {
9014: $first = int(1+rand(9));
9015: }
9016: $uname=$first.
1.1011 raeburn 9017: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9018: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9019: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9020: $uhome=&homeserver($uname,$udom,'true');
9021: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9022: return 'error: unable to generate unique course-ID';
9023: }
9024: }
9025: return $uname;
9026: }
9027:
1.813 albertel 9028: sub is_course {
1.1167 droeschl 9029: my ($cdom, $cnum) = scalar(@_) == 1 ?
9030: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9031:
9032: return unless $cdom and $cnum;
9033:
9034: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9035: '.');
9036:
1.1172.2.23 raeburn 9037: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9038: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9039: }
9040:
1.1015 raeburn 9041: sub store_userdata {
9042: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9043: my $result;
1.1016 raeburn 9044: if ($datakey ne '') {
1.1013 raeburn 9045: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9046: if ($udom eq '' || $uname eq '') {
9047: $udom = $env{'user.domain'};
9048: $uname = $env{'user.name'};
9049: }
9050: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9051: if (($uhome eq '') || ($uhome eq 'no_host')) {
9052: $result = 'error: no_host';
9053: } else {
9054: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9055: $storehash->{'host'} = $perlvar{'lonHostID'};
9056:
9057: my $namevalue='';
9058: foreach my $key (keys(%{$storehash})) {
9059: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9060: }
9061: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9062: unless ($namespace eq 'courserequests') {
9063: $datakey = &escape($datakey);
9064: }
1.1105 raeburn 9065: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9066: $namevalue,$uhome);
1.1013 raeburn 9067: }
9068: } else {
9069: $result = 'error: data to store was not a hash reference';
9070: }
9071: } else {
9072: $result= 'error: invalid requestkey';
9073: }
9074: return $result;
9075: }
9076:
1.21 www 9077: # ---------------------------------------------------------- Assign Custom Role
9078:
9079: sub assigncustomrole {
1.957 raeburn 9080: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9081: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9082: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9083: }
9084:
9085: # ----------------------------------------------------------------- Revoke Role
9086:
9087: sub revokerole {
1.957 raeburn 9088: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9089: my $now=time;
1.965 raeburn 9090: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9091: }
9092:
9093: # ---------------------------------------------------------- Revoke Custom Role
9094:
9095: sub revokecustomrole {
1.957 raeburn 9096: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9097: my $now=time;
1.357 www 9098: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9099: $deleteflag,$selfenroll,$context);
1.17 www 9100: }
9101:
1.533 banghart 9102: # ------------------------------------------------------------ Disk usage
1.535 albertel 9103: sub diskusage {
1.955 raeburn 9104: my ($udom,$uname,$directorypath,$getpropath)=@_;
9105: $directorypath =~ s/\/$//;
9106: my $listing=&reply('du2:'.&escape($directorypath).':'
9107: .&escape($getpropath).':'.&escape($uname).':'
9108: .&escape($udom),homeserver($uname,$udom));
9109: if ($listing eq 'unknown_cmd') {
9110: if ($getpropath) {
9111: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9112: }
9113: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9114: }
1.514 albertel 9115: return $listing;
1.512 banghart 9116: }
9117:
1.566 banghart 9118: sub is_locked {
1.1096 raeburn 9119: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9120: my @check;
9121: my $is_locked;
1.1093 raeburn 9122: push (@check,$file_name);
1.613 albertel 9123: my %locked = &get('file_permissions',\@check,
1.620 albertel 9124: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9125: my ($tmp)=keys(%locked);
9126: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9127:
1.566 banghart 9128: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9129: $is_locked = 'false';
9130: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9131: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9132: $is_locked = 'true';
1.1096 raeburn 9133: if (ref($which) eq 'ARRAY') {
9134: push(@{$which},$entry);
9135: } else {
9136: last;
9137: }
1.745 raeburn 9138: }
9139: }
1.566 banghart 9140: } else {
9141: $is_locked = 'false';
9142: }
1.1093 raeburn 9143: return $is_locked;
1.566 banghart 9144: }
9145:
1.759 albertel 9146: sub declutter_portfile {
9147: my ($file) = @_;
1.833 albertel 9148: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9149: return $file;
9150: }
9151:
1.559 banghart 9152: # ------------------------------------------------------------- Mark as Read Only
9153:
9154: sub mark_as_readonly {
9155: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9156: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9157: my ($tmp)=keys(%current_permissions);
9158: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9159: foreach my $file (@{$files}) {
1.759 albertel 9160: $file = &declutter_portfile($file);
1.561 banghart 9161: push(@{$current_permissions{$file}},$what);
1.559 banghart 9162: }
1.613 albertel 9163: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9164: return;
9165: }
9166:
1.572 banghart 9167: # ------------------------------------------------------------Save Selected Files
9168:
9169: sub save_selected_files {
9170: my ($user, $path, @files) = @_;
9171: my $filename = $user."savedfiles";
1.573 banghart 9172: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9173: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9174: foreach my $file (@files) {
1.620 albertel 9175: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9176: }
9177: foreach my $file (@other_files) {
1.574 banghart 9178: print (OUT $file."\n");
1.572 banghart 9179: }
1.574 banghart 9180: close (OUT);
1.572 banghart 9181: return 'ok';
9182: }
9183:
1.574 banghart 9184: sub clear_selected_files {
9185: my ($user) = @_;
9186: my $filename = $user."savedfiles";
1.1117 foxr 9187: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9188: print (OUT undef);
9189: close (OUT);
9190: return ("ok");
9191: }
9192:
1.572 banghart 9193: sub files_in_path {
9194: my ($user, $path) = @_;
9195: my $filename = $user."savedfiles";
9196: my %return_files;
1.1117 foxr 9197: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9198: while (my $line_in = <IN>) {
1.574 banghart 9199: chomp ($line_in);
9200: my @paths_and_file = split (m!/!, $line_in);
9201: my $file_part = pop (@paths_and_file);
9202: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9203: $path_part.='/';
9204: my $path_and_file = $path_part.$file_part;
9205: if ($path_part eq $path) {
9206: $return_files{$file_part}= 'selected';
9207: }
9208: }
1.574 banghart 9209: close (IN);
9210: return (\%return_files);
1.572 banghart 9211: }
9212:
9213: # called in portfolio select mode, to show files selected NOT in current directory
9214: sub files_not_in_path {
9215: my ($user, $path) = @_;
9216: my $filename = $user."savedfiles";
9217: my @return_files;
9218: my $path_part;
1.1117 foxr 9219: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9220: while (my $line = <IN>) {
1.572 banghart 9221: #ok, I know it's clunky, but I want it to work
1.800 albertel 9222: my @paths_and_file = split(m|/|, $line);
9223: my $file_part = pop(@paths_and_file);
9224: chomp($file_part);
9225: my $path_part = join('/', @paths_and_file);
1.572 banghart 9226: $path_part .= '/';
9227: my $path_and_file = $path_part.$file_part;
9228: if ($path_part ne $path) {
1.800 albertel 9229: push(@return_files, ($path_and_file));
1.572 banghart 9230: }
9231: }
1.800 albertel 9232: close(OUT);
1.574 banghart 9233: return (@return_files);
1.572 banghart 9234: }
9235:
1.745 raeburn 9236: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9237:
1.745 raeburn 9238: sub get_portfile_permissions {
9239: my ($domain,$user) = @_;
1.613 albertel 9240: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9241: my ($tmp)=keys(%current_permissions);
9242: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9243: return \%current_permissions;
9244: }
9245:
9246: #---------------------------------------------Get portfolio file access controls
9247:
1.749 raeburn 9248: sub get_access_controls {
1.745 raeburn 9249: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9250: my %access;
9251: my $real_file = $file;
9252: $file =~ s/\.meta$//;
1.745 raeburn 9253: if (defined($file)) {
1.749 raeburn 9254: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9255: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9256: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9257: }
9258: }
1.745 raeburn 9259: } else {
1.749 raeburn 9260: foreach my $key (keys(%{$current_permissions})) {
9261: if ($key =~ /\0accesscontrol$/) {
9262: if (defined($group)) {
9263: if ($key !~ m-^\Q$group\E/-) {
9264: next;
9265: }
9266: }
9267: my ($fullpath) = split(/\0/,$key);
9268: if (ref($$current_permissions{$key}) eq 'HASH') {
9269: foreach my $control (keys(%{$$current_permissions{$key}})) {
9270: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9271: }
9272: }
9273: }
9274: }
9275: }
9276: return %access;
9277: }
9278:
9279: sub modify_access_controls {
9280: my ($file_name,$changes,$domain,$user)=@_;
9281: my ($outcome,$deloutcome);
9282: my %store_permissions;
9283: my %new_values;
9284: my %new_control;
9285: my %translation;
9286: my @deletions = ();
9287: my $now = time;
9288: if (exists($$changes{'activate'})) {
9289: if (ref($$changes{'activate'}) eq 'HASH') {
9290: my @newitems = sort(keys(%{$$changes{'activate'}}));
9291: my $numnew = scalar(@newitems);
9292: for (my $i=0; $i<$numnew; $i++) {
9293: my $newkey = $newitems[$i];
9294: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9295: if ($newkey =~ /^\d+:/) {
9296: $newkey =~ s/^(\d+)/$newid/;
9297: $translation{$1} = $newid;
9298: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9299: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9300: $translation{$1} = $newid;
9301: }
1.749 raeburn 9302: $new_values{$file_name."\0".$newkey} =
9303: $$changes{'activate'}{$newitems[$i]};
9304: $new_control{$newkey} = $now;
9305: }
9306: }
9307: }
9308: my %todelete;
9309: my %changed_items;
9310: foreach my $action ('delete','update') {
9311: if (exists($$changes{$action})) {
9312: if (ref($$changes{$action}) eq 'HASH') {
9313: foreach my $key (keys(%{$$changes{$action}})) {
9314: my ($itemnum) = ($key =~ /^([^:]+):/);
9315: if ($action eq 'delete') {
9316: $todelete{$itemnum} = 1;
9317: } else {
9318: $changed_items{$itemnum} = $key;
9319: }
9320: }
1.745 raeburn 9321: }
9322: }
1.749 raeburn 9323: }
9324: # get lock on access controls for file.
9325: my $lockhash = {
9326: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9327: ':'.$env{'user.domain'},
9328: };
9329: my $tries = 0;
9330: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9331:
9332: while (($gotlock ne 'ok') && $tries <3) {
9333: $tries ++;
9334: sleep 1;
9335: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9336: }
9337: if ($gotlock eq 'ok') {
9338: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9339: my ($tmp)=keys(%curr_permissions);
9340: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9341: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9342: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9343: if (ref($curr_controls) eq 'HASH') {
9344: foreach my $control_item (keys(%{$curr_controls})) {
9345: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9346: if (defined($todelete{$itemnum})) {
9347: push(@deletions,$file_name."\0".$control_item);
9348: } else {
9349: if (defined($changed_items{$itemnum})) {
9350: $new_control{$changed_items{$itemnum}} = $now;
9351: push(@deletions,$file_name."\0".$control_item);
9352: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9353: } else {
9354: $new_control{$control_item} = $$curr_controls{$control_item};
9355: }
9356: }
1.745 raeburn 9357: }
9358: }
9359: }
1.970 raeburn 9360: my ($group);
9361: if (&is_course($domain,$user)) {
9362: ($group,my $file) = split(/\//,$file_name,2);
9363: }
1.749 raeburn 9364: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9365: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9366: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9367: # remove lock
9368: my @del_lock = ($file_name."\0".'locked_access_records');
9369: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9370: my $sqlresult =
1.970 raeburn 9371: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9372: $group);
1.749 raeburn 9373: } else {
9374: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9375: }
1.749 raeburn 9376: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9377: }
9378:
1.827 raeburn 9379: sub make_public_indefinitely {
9380: my ($requrl) = @_;
9381: my $now = time;
9382: my $action = 'activate';
9383: my $aclnum = 0;
9384: if (&is_portfolio_url($requrl)) {
9385: my (undef,$udom,$unum,$file_name,$group) =
9386: &parse_portfolio_url($requrl);
9387: my $current_perms = &get_portfile_permissions($udom,$unum);
9388: my %access_controls = &get_access_controls($current_perms,
9389: $group,$file_name);
9390: foreach my $key (keys(%{$access_controls{$file_name}})) {
9391: my ($num,$scope,$end,$start) =
9392: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9393: if ($scope eq 'public') {
9394: if ($start <= $now && $end == 0) {
9395: $action = 'none';
9396: } else {
9397: $action = 'update';
9398: $aclnum = $num;
9399: }
9400: last;
9401: }
9402: }
9403: if ($action eq 'none') {
9404: return 'ok';
9405: } else {
9406: my %changes;
9407: my $newend = 0;
9408: my $newstart = $now;
9409: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9410: $changes{$action}{$newkey} = {
9411: type => 'public',
9412: time => {
9413: start => $newstart,
9414: end => $newend,
9415: },
9416: };
9417: my ($outcome,$deloutcome,$new_values,$translation) =
9418: &modify_access_controls($file_name,\%changes,$udom,$unum);
9419: return $outcome;
9420: }
9421: } else {
9422: return 'invalid';
9423: }
9424: }
9425:
1.745 raeburn 9426: #------------------------------------------------------Get Marked as Read Only
9427:
9428: sub get_marked_as_readonly {
9429: my ($domain,$user,$what,$group) = @_;
9430: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9431: my @readonly_files;
1.629 banghart 9432: my $cmp1=$what;
9433: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9434: while (my ($file_name,$value) = each(%{$current_permissions})) {
9435: if (defined($group)) {
9436: if ($file_name !~ m-^\Q$group\E/-) {
9437: next;
9438: }
9439: }
1.561 banghart 9440: if (ref($value) eq "ARRAY"){
9441: foreach my $stored_what (@{$value}) {
1.629 banghart 9442: my $cmp2=$stored_what;
1.759 albertel 9443: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9444: $cmp2=join('',@{$stored_what});
1.745 raeburn 9445: }
1.629 banghart 9446: if ($cmp1 eq $cmp2) {
1.561 banghart 9447: push(@readonly_files, $file_name);
1.745 raeburn 9448: last;
1.563 banghart 9449: } elsif (!defined($what)) {
9450: push(@readonly_files, $file_name);
1.745 raeburn 9451: last;
1.561 banghart 9452: }
9453: }
1.745 raeburn 9454: }
1.561 banghart 9455: }
9456: return @readonly_files;
9457: }
1.577 banghart 9458: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9459:
1.577 banghart 9460: sub get_marked_as_readonly_hash {
1.745 raeburn 9461: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9462: my %readonly_files;
1.745 raeburn 9463: while (my ($file_name,$value) = each(%{$current_permissions})) {
9464: if (defined($group)) {
9465: if ($file_name !~ m-^\Q$group\E/-) {
9466: next;
9467: }
9468: }
1.577 banghart 9469: if (ref($value) eq "ARRAY"){
9470: foreach my $stored_what (@{$value}) {
1.745 raeburn 9471: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9472: foreach my $lock_descriptor(@{$stored_what}) {
9473: if ($lock_descriptor eq 'graded') {
9474: $readonly_files{$file_name} = 'graded';
9475: } elsif ($lock_descriptor eq 'handback') {
9476: $readonly_files{$file_name} = 'handback';
9477: } else {
9478: if (!exists($readonly_files{$file_name})) {
9479: $readonly_files{$file_name} = 'locked';
9480: }
9481: }
1.745 raeburn 9482: }
1.750 banghart 9483: }
1.577 banghart 9484: }
9485: }
9486: }
9487: return %readonly_files;
9488: }
1.559 banghart 9489: # ------------------------------------------------------------ Unmark as Read Only
9490:
9491: sub unmark_as_readonly {
1.629 banghart 9492: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9493: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9494: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9495: $file_name = &declutter_portfile($file_name);
1.634 albertel 9496: my $symb_crs = $what;
9497: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9498: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9499: my ($tmp)=keys(%current_permissions);
9500: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9501: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9502: foreach my $file (@readonly_files) {
1.759 albertel 9503: my $clean_file = &declutter_portfile($file);
9504: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9505: my $current_locks = $current_permissions{$file};
1.563 banghart 9506: my @new_locks;
9507: my @del_keys;
9508: if (ref($current_locks) eq "ARRAY"){
9509: foreach my $locker (@{$current_locks}) {
1.632 albertel 9510: my $compare=$locker;
1.749 raeburn 9511: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9512: $compare=join('',@{$locker});
1.746 raeburn 9513: if ($compare ne $symb_crs) {
9514: push(@new_locks, $locker);
9515: }
1.563 banghart 9516: }
9517: }
1.650 albertel 9518: if (scalar(@new_locks) > 0) {
1.563 banghart 9519: $current_permissions{$file} = \@new_locks;
9520: } else {
9521: push(@del_keys, $file);
1.613 albertel 9522: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9523: delete($current_permissions{$file});
1.563 banghart 9524: }
9525: }
1.561 banghart 9526: }
1.613 albertel 9527: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9528: return;
9529: }
1.512 banghart 9530:
1.17 www 9531: # ------------------------------------------------------------ Directory lister
9532:
9533: sub dirlist {
1.955 raeburn 9534: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9535: $uri=~s/^\///;
9536: $uri=~s/\/$//;
1.253 stredwic 9537: my ($udom, $uname);
1.955 raeburn 9538: if ($getuserdir) {
1.253 stredwic 9539: $udom = $userdomain;
9540: $uname = $username;
1.955 raeburn 9541: } else {
9542: (undef,$udom,$uname)=split(/\//,$uri);
9543: if(defined($userdomain)) {
9544: $udom = $userdomain;
9545: }
9546: if(defined($username)) {
9547: $uname = $username;
9548: }
1.253 stredwic 9549: }
1.955 raeburn 9550: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9551:
1.955 raeburn 9552: $dirRoot = $perlvar{'lonDocRoot'};
9553: if (defined($getpropath)) {
9554: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9555: $dirRoot =~ s/\/$//;
1.955 raeburn 9556: } elsif (defined($getuserdir)) {
9557: my $subdir=$uname.'__';
9558: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9559: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9560: ."/$udom/$subdir/$uname";
9561: } elsif (defined($alternateRoot)) {
9562: $dirRoot = $alternateRoot;
1.751 banghart 9563: }
1.253 stredwic 9564:
9565: if($udom) {
9566: if($uname) {
1.1135 raeburn 9567: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9568: if ($uhome eq 'no_host') {
9569: return ([],'no_host');
9570: }
1.955 raeburn 9571: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9572: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9573: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9574: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9575: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9576: } else {
9577: @listing_results = map { &unescape($_); } split(/:/,$listing);
9578: }
1.605 matthew 9579: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9580: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9581: @listing_results = split(/:/,$listing);
9582: } else {
9583: @listing_results = map { &unescape($_); } split(/:/,$listing);
9584: }
1.1135 raeburn 9585: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9586: ($listing eq 'rejected') || ($listing eq 'refused') ||
9587: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9588: return ([],$listing);
9589: } else {
9590: return (\@listing_results);
1.1135 raeburn 9591: }
1.955 raeburn 9592: } elsif(!$alternateRoot) {
1.1136 raeburn 9593: my (%allusers,%listerror);
1.841 albertel 9594: my %servers = &get_servers($udom,'library');
1.955 raeburn 9595: foreach my $tryserver (keys(%servers)) {
9596: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9597: &escape($udom),$tryserver);
9598: if ($listing eq 'unknown_cmd') {
9599: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9600: $udom, $tryserver);
9601: } else {
9602: @listing_results = map { &unescape($_); } split(/:/,$listing);
9603: }
1.841 albertel 9604: if ($listing eq 'unknown_cmd') {
9605: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9606: $udom, $tryserver);
9607: @listing_results = split(/:/,$listing);
9608: } else {
9609: @listing_results =
9610: map { &unescape($_); } split(/:/,$listing);
9611: }
1.1136 raeburn 9612: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9613: ($listing eq 'rejected') || ($listing eq 'refused') ||
9614: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9615: $listerror{$tryserver} = $listing;
9616: } else {
1.841 albertel 9617: foreach my $line (@listing_results) {
9618: my ($entry) = split(/&/,$line,2);
9619: $allusers{$entry} = 1;
9620: }
9621: }
1.253 stredwic 9622: }
1.1136 raeburn 9623: my @alluserslist=();
1.800 albertel 9624: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9625: push(@alluserslist,$user.'&user');
1.253 stredwic 9626: }
1.1136 raeburn 9627: return (\@alluserslist);
1.253 stredwic 9628: } else {
1.1136 raeburn 9629: return ([],'missing username');
1.253 stredwic 9630: }
1.955 raeburn 9631: } elsif(!defined($getpropath)) {
1.1136 raeburn 9632: my $path = $perlvar{'lonDocRoot'}.'/res/';
9633: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9634: return (\@all_domains);
1.955 raeburn 9635: } else {
1.1136 raeburn 9636: return ([],'missing domain');
1.275 stredwic 9637: }
9638: }
9639:
9640: # --------------------------------------------- GetFileTimestamp
9641: # This function utilizes dirlist and returns the date stamp for
9642: # when it was last modified. It will also return an error of -1
9643: # if an error occurs
9644:
9645: sub GetFileTimestamp {
1.955 raeburn 9646: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9647: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9648: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9649: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9650: undef,$getuserdir);
9651: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9652: return -1;
9653: }
9654: if (ref($fileref) eq 'ARRAY') {
9655: my @stats = split('&',$fileref->[0]);
1.375 matthew 9656: # @stats contains first the filename, then the stat output
9657: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9658: } else {
9659: return -1;
1.253 stredwic 9660: }
1.26 www 9661: }
9662:
1.712 albertel 9663: sub stat_file {
9664: my ($uri) = @_;
1.787 albertel 9665: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9666:
1.955 raeburn 9667: my ($udom,$uname,$file);
1.712 albertel 9668: if ($uri =~ m-^/(uploaded|editupload)/-) {
9669: ($udom,$uname,$file) =
1.811 albertel 9670: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9671: $file = 'userfiles/'.$file;
9672: }
9673: if ($uri =~ m-^/res/-) {
9674: ($udom,$uname) =
1.807 albertel 9675: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9676: $file = $uri;
9677: }
9678:
9679: if (!$udom || !$uname || !$file) {
9680: # unable to handle the uri
9681: return ();
9682: }
1.956 raeburn 9683: my $getpropath;
9684: if ($file =~ /^userfiles\//) {
9685: $getpropath = 1;
9686: }
1.1136 raeburn 9687: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9688: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9689: return ();
9690: } else {
9691: if (ref($listref) eq 'ARRAY') {
9692: my @stats = split('&',$listref->[0]);
9693: shift(@stats); #filename is first
9694: return @stats;
9695: }
1.712 albertel 9696: }
9697: return ();
9698: }
9699:
1.26 www 9700: # -------------------------------------------------------- Value of a Condition
9701:
1.713 albertel 9702: # gets the value of a specific preevaluated condition
9703: # stored in the string $env{user.state.<cid>}
9704: # or looks up a condition reference in the bighash and if if hasn't
9705: # already been evaluated recurses into docondval to get the value of
9706: # the condition, then memoizing it to
9707: # $env{user.state.<cid>.<condition>}
1.40 www 9708: sub directcondval {
9709: my $number=shift;
1.620 albertel 9710: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9711: &Apache::lonuserstate::evalstate();
9712: }
1.713 albertel 9713: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9714: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9715: } elsif ($number =~ /^_/) {
9716: my $sub_condition;
9717: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9718: &GDBM_READER(),0640)) {
9719: $sub_condition=$bighash{'conditions'.$number};
9720: untie(%bighash);
9721: }
9722: my $value = &docondval($sub_condition);
1.949 raeburn 9723: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9724: return $value;
9725: }
1.620 albertel 9726: if ($env{'user.state.'.$env{'request.course.id'}}) {
9727: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9728: } else {
9729: return 2;
9730: }
9731: }
9732:
1.713 albertel 9733: # get the collection of conditions for this resource
1.26 www 9734: sub condval {
9735: my $condidx=shift;
1.54 www 9736: my $allpathcond='';
1.713 albertel 9737: foreach my $cond (split(/\|/,$condidx)) {
9738: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9739: $allpathcond.=
9740: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9741: }
1.191 harris41 9742: }
1.54 www 9743: $allpathcond=~s/\|$//;
1.713 albertel 9744: return &docondval($allpathcond);
9745: }
9746:
9747: #evaluates an expression of conditions
9748: sub docondval {
9749: my ($allpathcond) = @_;
9750: my $result=0;
9751: if ($env{'request.course.id'}
9752: && defined($allpathcond)) {
9753: my $operand='|';
9754: my @stack;
9755: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9756: if ($chunk eq '(') {
9757: push @stack,($operand,$result);
9758: } elsif ($chunk eq ')') {
9759: my $before=pop @stack;
9760: if (pop @stack eq '&') {
9761: $result=$result>$before?$before:$result;
9762: } else {
9763: $result=$result>$before?$result:$before;
9764: }
9765: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9766: $operand=$chunk;
9767: } else {
9768: my $new=directcondval($chunk);
9769: if ($operand eq '&') {
9770: $result=$result>$new?$new:$result;
9771: } else {
9772: $result=$result>$new?$result:$new;
9773: }
9774: }
9775: }
1.26 www 9776: }
9777: return $result;
1.421 albertel 9778: }
9779:
9780: # ---------------------------------------------------- Devalidate courseresdata
9781:
9782: sub devalidatecourseresdata {
9783: my ($coursenum,$coursedomain)=@_;
9784: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9785: &devalidate_cache_new('courseres',$hashid);
1.28 www 9786: }
9787:
1.763 www 9788:
1.200 www 9789: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9790: #
9791: # Parameters:
9792: # $coursenum - Number of the course.
9793: # $coursedomain - Domain at which the course was created.
9794: # Returns:
9795: # A hash of the course parameters along (I think) with timestamps
9796: # and version info.
1.877 foxr 9797:
1.624 albertel 9798: sub get_courseresdata {
9799: my ($coursenum,$coursedomain)=@_;
1.200 www 9800: my $coursehom=&homeserver($coursenum,$coursedomain);
9801: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9802: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9803: my %dumpreply;
1.417 albertel 9804: unless (defined($cached)) {
1.624 albertel 9805: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9806: $result=\%dumpreply;
1.251 albertel 9807: my ($tmp) = keys(%dumpreply);
9808: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9809: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9810: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9811: return $tmp;
1.416 albertel 9812: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9813: $result=undef;
1.599 albertel 9814: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9815: }
9816: }
1.624 albertel 9817: return $result;
9818: }
9819:
1.633 albertel 9820: sub devalidateuserresdata {
9821: my ($uname,$udom)=@_;
9822: my $hashid="$udom:$uname";
9823: &devalidate_cache_new('userres',$hashid);
9824: }
9825:
1.624 albertel 9826: sub get_userresdata {
9827: my ($uname,$udom)=@_;
9828: #most student don\'t have any data set, check if there is some data
9829: if (&EXT_cache_status($udom,$uname)) { return undef; }
9830:
9831: my $hashid="$udom:$uname";
9832: my ($result,$cached)=&is_cached_new('userres',$hashid);
9833: if (!defined($cached)) {
9834: my %resourcedata=&dump('resourcedata',$udom,$uname);
9835: $result=\%resourcedata;
9836: &do_cache_new('userres',$hashid,$result,600);
9837: }
9838: my ($tmp)=keys(%$result);
9839: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9840: return $result;
9841: }
9842: #error 2 occurs when the .db doesn't exist
9843: if ($tmp!~/error: 2 /) {
1.672 albertel 9844: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9845: " Trying to get resource data for ".
9846: $uname." at ".$udom.": ".
9847: $tmp."</font>");
9848: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9849: #&EXT_cache_set($udom,$uname);
9850: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9851: undef($tmp); # not really an error so don't send it back
1.624 albertel 9852: }
9853: return $tmp;
9854: }
1.879 foxr 9855: #----------------------------------------------- resdata - return resource data
9856: # Purpose:
9857: # Return resource data for either users or for a course.
9858: # Parameters:
9859: # $name - Course/user name.
9860: # $domain - Name of the domain the user/course is registered on.
9861: # $type - Type of thing $name is (must be 'course' or 'user'
9862: # @which - Array of names of resources desired.
9863: # Returns:
9864: # The value of the first reasource in @which that is found in the
9865: # resource hash.
9866: # Exceptional Conditions:
9867: # If the $type passed in is not valid (not the string 'course' or
9868: # 'user', an undefined reference is returned.
9869: # If none of the resources are found, an undef is returned
1.624 albertel 9870: sub resdata {
9871: my ($name,$domain,$type,@which)=@_;
9872: my $result;
9873: if ($type eq 'course') {
9874: $result=&get_courseresdata($name,$domain);
9875: } elsif ($type eq 'user') {
9876: $result=&get_userresdata($name,$domain);
9877: }
9878: if (!ref($result)) { return $result; }
1.251 albertel 9879: foreach my $item (@which) {
1.927 albertel 9880: if (defined($result->{$item->[0]})) {
9881: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9882: }
1.250 albertel 9883: }
1.291 albertel 9884: return undef;
1.200 www 9885: }
9886:
1.1172.2.31 raeburn 9887: sub get_numsuppfiles {
9888: my ($cnum,$cdom,$ignorecache)=@_;
9889: my $hashid=$cnum.':'.$cdom;
9890: my ($suppcount,$cached);
9891: unless ($ignorecache) {
9892: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9893: }
9894: unless (defined($cached)) {
9895: my $chome=&homeserver($cnum,$cdom);
9896: unless ($chome eq 'no_host') {
9897: ($suppcount,my $errors) = (0,0);
9898: my $suppmap = 'supplemental.sequence';
9899: ($suppcount,$errors) =
9900: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9901: }
9902: &do_cache_new('suppcount',$hashid,$suppcount,600);
9903: }
9904: return $suppcount;
9905: }
9906:
1.379 matthew 9907: #
9908: # EXT resource caching routines
9909: #
9910:
9911: sub clear_EXT_cache_status {
1.383 albertel 9912: &delenv('cache.EXT.');
1.379 matthew 9913: }
9914:
9915: sub EXT_cache_status {
9916: my ($target_domain,$target_user) = @_;
1.383 albertel 9917: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9918: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9919: # We know already the user has no data
9920: return 1;
9921: } else {
9922: return 0;
9923: }
9924: }
9925:
9926: sub EXT_cache_set {
9927: my ($target_domain,$target_user) = @_;
1.383 albertel 9928: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9929: #&appenv({$cachename => time});
1.379 matthew 9930: }
9931:
1.28 www 9932: # --------------------------------------------------------- Value of a Variable
1.58 www 9933: sub EXT {
1.715 albertel 9934:
1.1172.2.28 raeburn 9935: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9936: unless ($varname) { return ''; }
1.218 albertel 9937: #get real user name/domain, courseid and symb
9938: my $courseid;
1.359 albertel 9939: my $publicuser;
1.427 www 9940: if ($symbparm) {
9941: $symbparm=&get_symb_from_alias($symbparm);
9942: }
1.218 albertel 9943: if (!($uname && $udom)) {
1.790 albertel 9944: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9945: if (!$symbparm) { $symbparm=$cursymb; }
9946: } else {
1.620 albertel 9947: $courseid=$env{'request.course.id'};
1.218 albertel 9948: }
1.48 www 9949: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9950: my $rest;
1.320 albertel 9951: if (defined($therest[0])) {
1.48 www 9952: $rest=join('.',@therest);
9953: } else {
9954: $rest='';
9955: }
1.320 albertel 9956:
1.57 www 9957: my $qualifierrest=$qualifier;
9958: if ($rest) { $qualifierrest.='.'.$rest; }
9959: my $spacequalifierrest=$space;
9960: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9961: if ($realm eq 'user') {
1.48 www 9962: # --------------------------------------------------------------- user.resource
9963: if ($space eq 'resource') {
1.651 albertel 9964: if ( (defined($Apache::lonhomework::parsing_a_problem)
9965: || defined($Apache::lonhomework::parsing_a_task))
9966: &&
1.744 albertel 9967: ($symbparm eq &symbread()) ) {
9968: # if we are in the middle of processing the resource the
9969: # get the value we are planning on committing
9970: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9971: return $Apache::lonhomework::results{$qualifierrest};
9972: } else {
9973: return $Apache::lonhomework::history{$qualifierrest};
9974: }
1.335 albertel 9975: } else {
1.359 albertel 9976: my %restored;
1.620 albertel 9977: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9978: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9979: } else {
9980: %restored=&restore($symbparm,$courseid,$udom,$uname);
9981: }
1.335 albertel 9982: return $restored{$qualifierrest};
9983: }
1.48 www 9984: # ----------------------------------------------------------------- user.access
9985: } elsif ($space eq 'access') {
1.218 albertel 9986: # FIXME - not supporting calls for a specific user
1.48 www 9987: return &allowed($qualifier,$rest);
9988: # ------------------------------------------ user.preferences, user.environment
9989: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9990: if (($uname eq $env{'user.name'}) &&
9991: ($udom eq $env{'user.domain'})) {
9992: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9993: } else {
1.359 albertel 9994: my %returnhash;
9995: if (!$publicuser) {
9996: %returnhash=&userenvironment($udom,$uname,
9997: $qualifierrest);
9998: }
1.218 albertel 9999: return $returnhash{$qualifierrest};
10000: }
1.48 www 10001: # ----------------------------------------------------------------- user.course
10002: } elsif ($space eq 'course') {
1.218 albertel 10003: # FIXME - not supporting calls for a specific user
1.620 albertel 10004: return $env{join('.',('request.course',$qualifier))};
1.48 www 10005: # ------------------------------------------------------------------- user.role
10006: } elsif ($space eq 'role') {
1.218 albertel 10007: # FIXME - not supporting calls for a specific user
1.620 albertel 10008: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10009: if ($qualifier eq 'value') {
10010: return $role;
10011: } elsif ($qualifier eq 'extent') {
10012: return $where;
10013: }
10014: # ----------------------------------------------------------------- user.domain
10015: } elsif ($space eq 'domain') {
1.218 albertel 10016: return $udom;
1.48 www 10017: # ------------------------------------------------------------------- user.name
10018: } elsif ($space eq 'name') {
1.218 albertel 10019: return $uname;
1.48 www 10020: # ---------------------------------------------------- Any other user namespace
1.29 www 10021: } else {
1.359 albertel 10022: my %reply;
10023: if (!$publicuser) {
10024: %reply=&get($space,[$qualifierrest],$udom,$uname);
10025: }
10026: return $reply{$qualifierrest};
1.48 www 10027: }
1.236 www 10028: } elsif ($realm eq 'query') {
10029: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10030: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10031: [$spacequalifierrest]);
1.620 albertel 10032: return $env{'form.'.$spacequalifierrest};
1.236 www 10033: } elsif ($realm eq 'request') {
1.48 www 10034: # ------------------------------------------------------------- request.browser
10035: if ($space eq 'browser') {
1.1145 bisitz 10036: return $env{'browser.'.$qualifier};
1.57 www 10037: # ------------------------------------------------------------ request.filename
10038: } else {
1.620 albertel 10039: return $env{'request.'.$spacequalifierrest};
1.29 www 10040: }
1.28 www 10041: } elsif ($realm eq 'course') {
1.48 www 10042: # ---------------------------------------------------------- course.description
1.620 albertel 10043: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10044: } elsif ($realm eq 'resource') {
1.165 www 10045:
1.620 albertel 10046: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10047: if (!$symbparm) { $symbparm=&symbread(); }
10048: }
1.693 albertel 10049:
1.1172.2.30 raeburn 10050: if ($qualifier eq '') {
10051: if ($space eq 'title') {
10052: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10053: return &gettitle($symbparm);
10054: }
1.693 albertel 10055:
1.1172.2.30 raeburn 10056: if ($space eq 'map') {
10057: my ($map) = &decode_symb($symbparm);
10058: return &symbread($map);
10059: }
10060: if ($space eq 'maptitle') {
10061: my ($map) = &decode_symb($symbparm);
10062: return &gettitle($map);
10063: }
10064: if ($space eq 'filename') {
10065: if ($symbparm) {
10066: return &clutter((&decode_symb($symbparm))[2]);
10067: }
10068: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10069: }
1.1172.2.30 raeburn 10070:
10071: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10072: if ($space eq 'visibleparts') {
10073: my $navmap = Apache::lonnavmaps::navmap->new();
10074: my $item;
10075: if (ref($navmap)) {
10076: my $res = $navmap->getBySymb($symbparm);
10077: my $parts = $res->parts();
10078: if (ref($parts) eq 'ARRAY') {
10079: $item = join(',',@{$parts});
10080: }
10081: undef($navmap);
10082: }
10083: return $item;
10084: }
10085: }
10086: }
1.693 albertel 10087:
10088: my ($section, $group, @groups);
1.593 albertel 10089: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10090: if (($courseid eq '') && ($cid)) {
10091: $courseid = $cid;
10092: }
10093: if (($symbparm && $courseid) &&
10094: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10095:
1.218 albertel 10096: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10097:
1.60 www 10098: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10099: my $symbp=$symbparm;
1.735 albertel 10100: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10101:
10102: my $symbparm=$symbp.'.'.$spacequalifierrest;
10103: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10104:
1.620 albertel 10105: if (($env{'user.name'} eq $uname) &&
10106: ($env{'user.domain'} eq $udom)) {
10107: $section=$env{'request.course.sec'};
1.733 raeburn 10108: @groups = split(/:/,$env{'request.course.groups'});
10109: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10110: } else {
1.539 albertel 10111: if (! defined($usection)) {
1.551 albertel 10112: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10113: } else {
10114: $section = $usection;
10115: }
1.733 raeburn 10116: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10117: }
10118:
10119: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10120: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10121: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10122:
1.593 albertel 10123: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10124: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10125: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10126:
1.60 www 10127: # ----------------------------------------------------------- first, check user
1.624 albertel 10128:
10129: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10130: ([$courselevelr,'resource'],
10131: [$courselevelm,'map' ],
10132: [$courselevel, 'course' ]));
1.931 albertel 10133: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10134:
1.594 albertel 10135: # ------------------------------------------------ second, check some of course
1.684 raeburn 10136: my $coursereply;
1.691 raeburn 10137: if (@groups > 0) {
10138: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10139: $mapparm,$spacequalifierrest);
1.927 albertel 10140: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10141: }
1.96 www 10142:
1.684 raeburn 10143: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10144: $env{'course.'.$courseid.'.domain'},
10145: 'course',
10146: ([$seclevelr, 'resource'],
10147: [$seclevelm, 'map' ],
10148: [$seclevel, 'course' ],
10149: [$courselevelr,'resource']));
10150: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10151:
1.60 www 10152: # ------------------------------------------------------ third, check map parms
1.218 albertel 10153: my %parmhash=();
10154: my $thisparm='';
10155: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10156: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10157: &GDBM_READER(),0640)) {
1.218 albertel 10158: $thisparm=$parmhash{$symbparm};
10159: untie(%parmhash);
10160: }
1.927 albertel 10161: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10162: }
1.594 albertel 10163: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10164:
1.218 albertel 10165: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10166: my $filename;
10167: if (!$symbparm) { $symbparm=&symbread(); }
10168: if ($symbparm) {
1.409 www 10169: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10170: } else {
1.620 albertel 10171: $filename=$env{'request.filename'};
1.282 albertel 10172: }
10173: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10174: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10175: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10176: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10177:
1.927 albertel 10178: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10179: if ($symbparm && defined($courseid) &&
1.620 albertel 10180: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10181: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10182: $env{'course.'.$courseid.'.domain'},
10183: 'course',
1.927 albertel 10184: ([$courselevelm,'map' ],
10185: [$courselevel, 'course']));
10186: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10187: }
1.145 www 10188: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10189: unless ($space eq '0') {
1.336 albertel 10190: my @parts=split(/_/,$space);
10191: my $id=pop(@parts);
10192: my $part=join('_',@parts);
10193: if ($part eq '') { $part='0'; }
1.927 albertel 10194: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10195: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10196: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10197: }
1.395 albertel 10198: if ($recurse) { return undef; }
10199: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10200: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10201: # ---------------------------------------------------- Any other user namespace
10202: } elsif ($realm eq 'environment') {
10203: # ----------------------------------------------------------------- environment
1.620 albertel 10204: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10205: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10206: } else {
1.770 albertel 10207: if ($uname eq 'anonymous' && $udom eq '') {
10208: return '';
10209: }
1.219 albertel 10210: my %returnhash=&userenvironment($udom,$uname,
10211: $spacequalifierrest);
10212: return $returnhash{$spacequalifierrest};
10213: }
1.28 www 10214: } elsif ($realm eq 'system') {
1.48 www 10215: # ----------------------------------------------------------------- system.time
10216: if ($space eq 'time') {
10217: return time;
10218: }
1.696 albertel 10219: } elsif ($realm eq 'server') {
10220: # ----------------------------------------------------------------- system.time
10221: if ($space eq 'name') {
10222: return $ENV{'SERVER_NAME'};
10223: }
1.28 www 10224: }
1.48 www 10225: return '';
1.61 www 10226: }
10227:
1.927 albertel 10228: sub get_reply {
10229: my ($reply_value) = @_;
1.940 raeburn 10230: if (ref($reply_value) eq 'ARRAY') {
10231: if (wantarray) {
10232: return @$reply_value;
10233: }
10234: return $reply_value->[0];
10235: } else {
10236: return $reply_value;
1.927 albertel 10237: }
10238: }
10239:
1.691 raeburn 10240: sub check_group_parms {
10241: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10242: my @groupitems = ();
10243: my $resultitem;
1.927 albertel 10244: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10245: foreach my $group (@{$groups}) {
10246: foreach my $level (@levels) {
1.927 albertel 10247: my $item = $courseid.'.['.$group.'].'.$level->[0];
10248: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10249: }
10250: }
10251: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10252: $env{'course.'.$courseid.'.domain'},
10253: 'course',@groupitems);
10254: return $coursereply;
10255: }
10256:
10257: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10258: my ($courseid,@groups) = @_;
10259: @groups = sort(@groups);
1.691 raeburn 10260: return @groups;
10261: }
10262:
1.395 albertel 10263: sub packages_tab_default {
10264: my ($uri,$varname)=@_;
10265: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10266:
10267: my (@extension,@specifics,$do_default);
10268: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10269: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10270: if ($pack_type eq 'default') {
10271: $do_default=1;
10272: } elsif ($pack_type eq 'extension') {
10273: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10274: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10275: # only look at packages defaults for packages that this id is
1.738 albertel 10276: push(@specifics,[$package,$pack_type,$pack_part]);
10277: }
10278: }
10279: # first look for a package that matches the requested part id
10280: foreach my $package (@specifics) {
10281: my (undef,$pack_type,$pack_part)=@{$package};
10282: next if ($pack_part ne $part);
10283: if (defined($packagetab{"$pack_type&$name&default"})) {
10284: return $packagetab{"$pack_type&$name&default"};
10285: }
10286: }
10287: # look for any possible matching non extension_ package
10288: foreach my $package (@specifics) {
10289: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10290: if (defined($packagetab{"$pack_type&$name&default"})) {
10291: return $packagetab{"$pack_type&$name&default"};
10292: }
1.585 albertel 10293: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10294: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10295: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10296: }
10297: }
1.738 albertel 10298: # look for any posible extension_ match
10299: foreach my $package (@extension) {
10300: my ($package,$pack_type)=@{$package};
10301: if (defined($packagetab{"$pack_type&$name&default"})) {
10302: return $packagetab{"$pack_type&$name&default"};
10303: }
10304: if (defined($packagetab{$package."&$name&default"})) {
10305: return $packagetab{$package."&$name&default"};
10306: }
10307: }
10308: # look for a global default setting
10309: if ($do_default && defined($packagetab{"default&$name&default"})) {
10310: return $packagetab{"default&$name&default"};
10311: }
1.395 albertel 10312: return undef;
10313: }
10314:
1.334 albertel 10315: sub add_prefix_and_part {
10316: my ($prefix,$part)=@_;
10317: my $keyroot;
10318: if (defined($prefix) && $prefix !~ /^__/) {
10319: # prefix that has a part already
10320: $keyroot=$prefix;
10321: } elsif (defined($prefix)) {
10322: # prefix that is missing a part
10323: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10324: } else {
10325: # no prefix at all
10326: if (defined($part)) { $keyroot='_'.$part; }
10327: }
10328: return $keyroot;
10329: }
10330:
1.71 www 10331: # ---------------------------------------------------------------- Get metadata
10332:
1.599 albertel 10333: my %metaentry;
1.1070 www 10334: my %importedpartids;
1.71 www 10335: sub metadata {
1.176 www 10336: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10337: $uri=&declutter($uri);
1.288 albertel 10338: # if it is a non metadata possible uri return quickly
1.529 albertel 10339: if (($uri eq '') ||
10340: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10341: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10342: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10343: return undef;
10344: }
1.1172.2.49 raeburn 10345: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10346: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10347: return undef;
1.288 albertel 10348: }
1.73 www 10349: my $filename=$uri;
10350: $uri=~s/\.meta$//;
1.172 www 10351: #
10352: # Is the metadata already cached?
1.177 www 10353: # Look at timestamp of caching
1.172 www 10354: # Everything is cached by the main uri, libraries are never directly cached
10355: #
1.428 albertel 10356: if (!defined($liburi)) {
1.599 albertel 10357: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10358: if (defined($cached)) { return $result->{':'.$what}; }
10359: }
10360: {
1.1069 www 10361: # Imported parts would go here
1.1070 www 10362: my %importedids=();
10363: my @origfileimportpartids=();
1.1069 www 10364: my $importedparts=0;
1.172 www 10365: #
10366: # Is this a recursive call for a library?
10367: #
1.599 albertel 10368: # if (! exists($metacache{$uri})) {
10369: # $metacache{$uri}={};
10370: # }
1.924 albertel 10371: my $cachetime = 60*60;
1.171 www 10372: if ($liburi) {
10373: $liburi=&declutter($liburi);
10374: $filename=$liburi;
1.401 bowersj2 10375: } else {
1.599 albertel 10376: &devalidate_cache_new('meta',$uri);
10377: undef(%metaentry);
1.401 bowersj2 10378: }
1.140 www 10379: my %metathesekeys=();
1.73 www 10380: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10381: my $metastring;
1.1140 www 10382: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10383: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10384: $metastring =
1.929 albertel 10385: &Apache::lonnet::ssi_body($which,
1.924 albertel 10386: ('grade_target' => 'meta'));
10387: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10388: } elsif (($uri !~ m -^(editupload)/-) &&
10389: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10390: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10391: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10392: $metastring=&getfile($file);
1.489 albertel 10393: }
1.208 albertel 10394: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10395: my $token;
1.140 www 10396: undef %metathesekeys;
1.71 www 10397: while ($token=$parser->get_token) {
1.339 albertel 10398: if ($token->[0] eq 'S') {
10399: if (defined($token->[2]->{'package'})) {
1.172 www 10400: #
10401: # This is a package - get package info
10402: #
1.339 albertel 10403: my $package=$token->[2]->{'package'};
10404: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10405: if (defined($token->[2]->{'id'})) {
10406: $keyroot.='_'.$token->[2]->{'id'};
10407: }
1.599 albertel 10408: if ($metaentry{':packages'}) {
10409: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10410: } else {
1.599 albertel 10411: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10412: }
1.736 albertel 10413: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10414: my $part=$keyroot;
10415: $part=~s/^\_//;
1.736 albertel 10416: if ($pack_entry=~/^\Q$package\E\&/ ||
10417: $pack_entry=~/^\Q$package\E_0\&/) {
10418: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10419: # ignore package.tab specified default values
10420: # here &package_tab_default() will fetch those
10421: if ($subp eq 'default') { next; }
1.736 albertel 10422: my $value=$packagetab{$pack_entry};
1.432 albertel 10423: my $unikey;
10424: if ($pack =~ /_0$/) {
10425: $unikey='parameter_0_'.$name;
10426: $part=0;
10427: } else {
10428: $unikey='parameter'.$keyroot.'_'.$name;
10429: }
1.339 albertel 10430: if ($subp eq 'display') {
10431: $value.=' [Part: '.$part.']';
10432: }
1.599 albertel 10433: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10434: $metathesekeys{$unikey}=1;
1.599 albertel 10435: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10436: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10437: }
1.599 albertel 10438: if (defined($metaentry{':'.$unikey.'.default'})) {
10439: $metaentry{':'.$unikey}=
10440: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10441: }
1.339 albertel 10442: }
10443: }
10444: } else {
1.172 www 10445: #
10446: # This is not a package - some other kind of start tag
1.339 albertel 10447: #
10448: my $entry=$token->[1];
1.1068 www 10449: my $unikey='';
1.175 www 10450:
1.339 albertel 10451: if ($entry eq 'import') {
1.175 www 10452: #
10453: # Importing a library here
1.339 albertel 10454: #
1.1067 www 10455: my $location=$parser->get_text('/import');
10456: my $dir=$filename;
10457: $dir=~s|[^/]*$||;
10458: $location=&filelocation($dir,$location);
1.1069 www 10459:
1.1068 www 10460: my $importmode=$token->[2]->{'importmode'};
10461: if ($importmode eq 'problem') {
1.1069 www 10462: # Import as problem/response
1.1068 www 10463: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10464: } elsif ($importmode eq 'part') {
10465: # Import as part(s)
1.1069 www 10466: $importedparts=1;
10467: # We need to get the original file and the imported file to get the part order correct
10468: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10469: # Load and inspect original file
1.1070 www 10470: if ($#origfileimportpartids<0) {
10471: undef(%importedpartids);
10472: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10473: my $origfile=&getfile($origfilelocation);
10474: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10475: }
10476:
1.1069 www 10477: # Load and inspect imported file
10478: my $impfile=&getfile($location);
10479: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10480: if ($#impfilepartids>=0) {
10481: # This problem had parts
1.1070 www 10482: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10483: } else {
10484: # Importing by turning a single problem into a problem part
10485: # It gets the import-tags ID as part-ID
10486: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10487: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10488: }
1.1068 www 10489: } else {
10490: # Normal import
10491: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10492: if (defined($token->[2]->{'id'})) {
10493: $unikey.='_'.$token->[2]->{'id'};
10494: }
1.1067 www 10495: }
10496:
1.339 albertel 10497: if ($depthcount<20) {
1.736 albertel 10498: my $metadata =
10499: &metadata($uri,'keys', $location,$unikey,
10500: $depthcount+1);
10501: foreach my $meta (split(',',$metadata)) {
10502: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10503: $metathesekeys{$meta}=1;
1.339 albertel 10504: }
1.1068 www 10505:
10506: }
1.1067 www 10507: } else {
10508: #
10509: # Not importing, some other kind of non-package, non-library start tag
10510: #
10511: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10512: if (defined($token->[2]->{'id'})) {
10513: $unikey.='_'.$token->[2]->{'id'};
10514: }
1.339 albertel 10515: if (defined($token->[2]->{'name'})) {
10516: $unikey.='_'.$token->[2]->{'name'};
10517: }
10518: $metathesekeys{$unikey}=1;
1.736 albertel 10519: foreach my $param (@{$token->[3]}) {
10520: $metaentry{':'.$unikey.'.'.$param} =
10521: $token->[2]->{$param};
1.339 albertel 10522: }
10523: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10524: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10525: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10526: # only ws inside the tag, and not in default, so use default
10527: # as value
1.599 albertel 10528: $metaentry{':'.$unikey}=$default;
1.908 albertel 10529: } elsif ( $internaltext =~ /\S/ ) {
10530: # something interesting inside the tag
10531: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10532: } else {
1.908 albertel 10533: # no interesting values, don't set a default
1.339 albertel 10534: }
1.172 www 10535: # end of not-a-package not-a-library import
1.339 albertel 10536: }
1.172 www 10537: # end of not-a-package start tag
1.339 albertel 10538: }
1.172 www 10539: # the next is the end of "start tag"
1.339 albertel 10540: }
10541: }
1.483 albertel 10542: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10543: $extension = lc($extension);
10544: if ($extension eq 'htm') { $extension='html'; }
10545:
1.737 albertel 10546: foreach my $key (keys(%packagetab)) {
1.483 albertel 10547: #no specific packages #how's our extension
10548: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10549: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10550: \%metathesekeys);
10551: }
1.883 albertel 10552:
10553: if (!exists($metaentry{':packages'})
10554: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10555: foreach my $key (keys(%packagetab)) {
1.483 albertel 10556: #no specific packages well let's get default then
10557: if ($key!~/^default&/) { next; }
1.488 albertel 10558: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10559: \%metathesekeys);
10560: }
10561: }
1.338 www 10562: # are there custom rights to evaluate
1.599 albertel 10563: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10564:
1.338 www 10565: #
10566: # Importing a rights file here
1.339 albertel 10567: #
10568: unless ($depthcount) {
1.599 albertel 10569: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10570: my $dir=$filename;
10571: $dir=~s|[^/]*$||;
10572: $location=&filelocation($dir,$location);
1.736 albertel 10573: my $rights_metadata =
10574: &metadata($uri,'keys',$location,'_rights',
10575: $depthcount+1);
10576: foreach my $rights (split(',',$rights_metadata)) {
10577: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10578: $metathesekeys{$rights}=1;
1.339 albertel 10579: }
10580: }
10581: }
1.737 albertel 10582: # uniqifiy package listing
10583: my %seen;
10584: my @uniq_packages =
10585: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10586: $metaentry{':packages'} = join(',',@uniq_packages);
10587:
1.1070 www 10588: if ($importedparts) {
10589: # We had imported parts and need to rebuild partorder
10590: $metaentry{':partorder'}='';
10591: $metathesekeys{'partorder'}=1;
10592: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10593: if ($origfileimportpartids[$index] eq 'part') {
10594: # original part, part of the problem
10595: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10596: } else {
10597: # we have imported parts at this position
10598: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10599: }
10600: }
10601: $metaentry{':partorder'}=~s/^\,//;
10602: }
10603:
1.737 albertel 10604: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10605: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10606: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10607: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10608: # this is the end of "was not already recently cached
1.71 www 10609: }
1.599 albertel 10610: return $metaentry{':'.$what};
1.261 albertel 10611: }
10612:
1.488 albertel 10613: sub metadata_create_package_def {
1.483 albertel 10614: my ($uri,$key,$package,$metathesekeys)=@_;
10615: my ($pack,$name,$subp)=split(/\&/,$key);
10616: if ($subp eq 'default') { next; }
10617:
1.599 albertel 10618: if (defined($metaentry{':packages'})) {
10619: $metaentry{':packages'}.=','.$package;
1.483 albertel 10620: } else {
1.599 albertel 10621: $metaentry{':packages'}=$package;
1.483 albertel 10622: }
10623: my $value=$packagetab{$key};
10624: my $unikey;
10625: $unikey='parameter_0_'.$name;
1.599 albertel 10626: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10627: $$metathesekeys{$unikey}=1;
1.599 albertel 10628: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10629: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10630: }
1.599 albertel 10631: if (defined($metaentry{':'.$unikey.'.default'})) {
10632: $metaentry{':'.$unikey}=
10633: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10634: }
10635: }
10636:
1.261 albertel 10637: sub metadata_generate_part0 {
10638: my ($metadata,$metacache,$uri) = @_;
10639: my %allnames;
1.737 albertel 10640: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10641: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10642: my $part=$$metacache{':'.$metakey.'.part'};
10643: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10644: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10645: $allnames{$name}=$part;
10646: }
10647: }
10648: }
10649: foreach my $name (keys(%allnames)) {
10650: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10651: my $key=":parameter_0_$name";
1.261 albertel 10652: $$metacache{"$key.part"}='0';
10653: $$metacache{"$key.name"}=$name;
1.428 albertel 10654: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10655: $allnames{$name}.'_'.$name.
10656: '.type'};
1.428 albertel 10657: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10658: '.display'};
1.644 www 10659: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10660: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10661: $$metacache{"$key.display"}=$olddis;
10662: }
1.71 www 10663: }
10664:
1.764 albertel 10665: # ------------------------------------------------------ Devalidate title cache
10666:
10667: sub devalidate_title_cache {
10668: my ($url)=@_;
10669: if (!$env{'request.course.id'}) { return; }
10670: my $symb=&symbread($url);
10671: if (!$symb) { return; }
10672: my $key=$env{'request.course.id'}."\0".$symb;
10673: &devalidate_cache_new('title',$key);
10674: }
10675:
1.1014 droeschl 10676: # ------------------------------------------------- Get the title of a course
10677:
10678: sub current_course_title {
10679: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10680: }
1.301 www 10681: # ------------------------------------------------- Get the title of a resource
10682:
10683: sub gettitle {
10684: my $urlsymb=shift;
10685: my $symb=&symbread($urlsymb);
1.534 albertel 10686: if ($symb) {
1.620 albertel 10687: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10688: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10689: if (defined($cached)) {
10690: return $result;
10691: }
1.534 albertel 10692: my ($map,$resid,$url)=&decode_symb($symb);
10693: my $title='';
1.907 albertel 10694: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10695: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10696: } else {
10697: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10698: &GDBM_READER(),0640)) {
10699: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10700: $title=$bighash{'title_'.$mapid.'.'.$resid};
10701: untie(%bighash);
10702: }
1.534 albertel 10703: }
10704: $title=~s/\&colon\;/\:/gs;
10705: if ($title) {
1.1159 www 10706: # Remember both $symb and $title for dynamic metadata
10707: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10708: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10709: # Cache this title and then return it
1.599 albertel 10710: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10711: }
10712: $urlsymb=$url;
10713: }
10714: my $title=&metadata($urlsymb,'title');
10715: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10716: return $title;
1.301 www 10717: }
1.613 albertel 10718:
1.614 albertel 10719: sub get_slot {
10720: my ($which,$cnum,$cdom)=@_;
10721: if (!$cnum || !$cdom) {
1.790 albertel 10722: (undef,my $courseid)=&whichuser();
1.620 albertel 10723: $cdom=$env{'course.'.$courseid.'.domain'};
10724: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10725: }
1.703 albertel 10726: my $key=join("\0",'slots',$cdom,$cnum,$which);
10727: my %slotinfo;
10728: if (exists($remembered{$key})) {
10729: $slotinfo{$which} = $remembered{$key};
10730: } else {
10731: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10732: &Apache::lonhomework::showhash(%slotinfo);
10733: my ($tmp)=keys(%slotinfo);
10734: if ($tmp=~/^error:/) { return (); }
10735: $remembered{$key} = $slotinfo{$which};
10736: }
1.616 albertel 10737: if (ref($slotinfo{$which}) eq 'HASH') {
10738: return %{$slotinfo{$which}};
10739: }
10740: return $slotinfo{$which};
1.614 albertel 10741: }
1.1150 raeburn 10742:
10743: sub get_reservable_slots {
10744: my ($cnum,$cdom,$uname,$udom) = @_;
10745: my $now = time;
10746: my $reservable_info;
10747: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10748: if (exists($remembered{$key})) {
10749: $reservable_info = $remembered{$key};
10750: } else {
10751: my %resv;
10752: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10753: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10754: $reservable_info = \%resv;
10755: $remembered{$key} = $reservable_info;
10756: }
10757: return $reservable_info;
10758: }
10759:
10760: sub get_course_slots {
10761: my ($cnum,$cdom) = @_;
10762: my $hashid=$cnum.':'.$cdom;
10763: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10764: if (defined($cached)) {
10765: if (ref($result) eq 'HASH') {
10766: return %{$result};
10767: }
10768: } else {
10769: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10770: my ($tmp) = keys(%slots);
10771: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10772: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10773: return %slots;
10774: }
10775: }
10776: return;
10777: }
10778:
10779: sub devalidate_slots_cache {
10780: my ($cnum,$cdom)=@_;
10781: my $hashid=$cnum.':'.$cdom;
10782: &devalidate_cache_new('allslots',$hashid);
10783: }
10784:
1.1172.2.8 raeburn 10785: sub get_coursechange {
10786: my ($cdom,$cnum) = @_;
10787: if ($cdom eq '' || $cnum eq '') {
10788: return unless ($env{'request.course.id'});
10789: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10790: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10791: }
10792: my $hashid=$cdom.'_'.$cnum;
10793: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10794: if ((defined($cached)) && ($change ne '')) {
10795: return $change;
10796: } else {
10797: my %crshash;
10798: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10799: if ($crshash{'internal.contentchange'} eq '') {
10800: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10801: if ($change eq '') {
10802: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10803: $change = $crshash{'internal.created'};
10804: }
10805: } else {
10806: $change = $crshash{'internal.contentchange'};
10807: }
10808: my $cachetime = 600;
10809: &do_cache_new('crschange',$hashid,$change,$cachetime);
10810: }
10811: return $change;
10812: }
10813:
10814: sub devalidate_coursechange_cache {
10815: my ($cnum,$cdom)=@_;
10816: my $hashid=$cnum.':'.$cdom;
10817: &devalidate_cache_new('crschange',$hashid);
10818: }
10819:
1.31 www 10820: # ------------------------------------------------- Update symbolic store links
10821:
10822: sub symblist {
10823: my ($mapname,%newhash)=@_;
1.438 www 10824: $mapname=&deversion(&declutter($mapname));
1.31 www 10825: my %hash;
1.620 albertel 10826: if (($env{'request.course.fn'}) && (%newhash)) {
10827: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10828: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10829: foreach my $url (keys(%newhash)) {
1.711 albertel 10830: next if ($url eq 'last_known'
10831: && $env{'form.no_update_last_known'});
10832: $hash{declutter($url)}=&encode_symb($mapname,
10833: $newhash{$url}->[1],
10834: $newhash{$url}->[0]);
1.191 harris41 10835: }
1.31 www 10836: if (untie(%hash)) {
10837: return 'ok';
10838: }
10839: }
10840: }
10841: return 'error';
1.212 www 10842: }
10843:
10844: # --------------------------------------------------------------- Verify a symb
10845:
10846: sub symbverify {
1.1172.2.11 raeburn 10847: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10848: my $thisfn=$thisurl;
1.439 www 10849: $thisfn=&declutter($thisfn);
1.215 www 10850: # direct jump to resource in page or to a sequence - will construct own symbs
10851: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10852: # check URL part
1.409 www 10853: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10854:
1.431 www 10855: unless ($url eq $thisfn) { return 0; }
1.213 www 10856:
1.216 www 10857: $symb=&symbclean($symb);
1.510 www 10858: $thisurl=&deversion($thisurl);
1.439 www 10859: $thisfn=&deversion($thisfn);
1.213 www 10860:
10861: my %bighash;
10862: my $okay=0;
1.431 www 10863:
1.620 albertel 10864: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10865: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10866: my $noclutter;
1.1032 raeburn 10867: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10868: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10869: if ($map =~ m{^uploaded/.+\.page$}) {
10870: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10871: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10872: $noclutter = 1;
10873: }
10874: }
10875: my $ids;
10876: if ($noclutter) {
10877: $ids=$bighash{'ids_'.$thisurl};
10878: } else {
10879: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10880: }
1.1102 raeburn 10881: unless ($ids) {
1.1172.2.13 raeburn 10882: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10883: $ids=$bighash{$idkey};
1.216 www 10884: }
10885: if ($ids) {
10886: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10887: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10888: $symb =~ s/\?.+$//;
10889: }
1.800 albertel 10890: foreach my $id (split(/\,/,$ids)) {
10891: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10892: if (
10893: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10894: eq $symb) {
1.1172.2.11 raeburn 10895: if (ref($encstate)) {
10896: $$encstate = $bighash{'encrypted_'.$id};
10897: }
1.1172.2.13 raeburn 10898: if (($env{'request.role.adv'}) ||
10899: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10900: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10901: $okay=1;
10902: last;
10903: }
10904: }
10905: }
1.216 www 10906: }
1.213 www 10907: untie(%bighash);
10908: }
10909: return $okay;
1.31 www 10910: }
10911:
1.210 www 10912: # --------------------------------------------------------------- Clean-up symb
10913:
10914: sub symbclean {
10915: my $symb=shift;
1.568 albertel 10916: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10917: # remove version from map
10918: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10919:
1.210 www 10920: # remove version from URL
10921: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10922:
1.507 www 10923: # remove wrapper
10924:
1.510 www 10925: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10926: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10927: return $symb;
1.409 www 10928: }
10929:
10930: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10931:
10932: sub encode_symb {
10933: my ($map,$resid,$url)=@_;
10934: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10935: }
1.409 www 10936:
10937: sub decode_symb {
1.568 albertel 10938: my $symb=shift;
10939: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10940: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10941: return (&fixversion($map),$resid,&fixversion($url));
10942: }
10943:
10944: sub fixversion {
10945: my $fn=shift;
1.609 banghart 10946: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10947: my %bighash;
10948: my $uri=&clutter($fn);
1.620 albertel 10949: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10950: # is this cached?
1.599 albertel 10951: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10952: if (defined($cached)) { return $result; }
10953: # unfortunately not cached, or expired
1.620 albertel 10954: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10955: &GDBM_READER(),0640)) {
10956: if ($bighash{'version_'.$uri}) {
10957: my $version=$bighash{'version_'.$uri};
1.444 www 10958: unless (($version eq 'mostrecent') ||
10959: ($version==&getversion($uri))) {
1.440 www 10960: $uri=~s/\.(\w+)$/\.$version\.$1/;
10961: }
10962: }
10963: untie %bighash;
1.413 www 10964: }
1.599 albertel 10965: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10966: }
10967:
10968: sub deversion {
10969: my $url=shift;
10970: $url=~s/\.\d+\.(\w+)$/\.$1/;
10971: return $url;
1.210 www 10972: }
10973:
1.31 www 10974: # ------------------------------------------------------ Return symb list entry
10975:
10976: sub symbread {
1.249 www 10977: my ($thisfn,$donotrecurse)=@_;
1.1172.2.54 raeburn 10978: my $cache_str='request.symbread.cached.'.$thisfn;
10979: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 10980: # no filename provided? try from environment
1.1172.2.54 raeburn 10981: unless ($thisfn) {
1.620 albertel 10982: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10983: return $env{$cache_str}=&symbclean($env{'request.symb'});
10984: }
10985: $thisfn=$env{'request.filename'};
1.44 www 10986: }
1.569 albertel 10987: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10988: # is that filename actually a symb? Verify, clean, and return
10989: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10990: if (&symbverify($thisfn,$1)) {
1.620 albertel 10991: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10992: }
1.242 www 10993: }
1.44 www 10994: $thisfn=declutter($thisfn);
1.31 www 10995: my %hash;
1.37 www 10996: my %bighash;
10997: my $syval='';
1.620 albertel 10998: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10999: my $targetfn = $thisfn;
1.609 banghart 11000: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11001: $targetfn = 'adm/wrapper/'.$thisfn;
11002: }
1.687 albertel 11003: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11004: $targetfn=$1;
11005: }
1.620 albertel 11006: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11007: &GDBM_READER(),0640)) {
1.481 raeburn 11008: $syval=$hash{$targetfn};
1.37 www 11009: untie(%hash);
11010: }
11011: # ---------------------------------------------------------- There was an entry
11012: if ($syval) {
1.601 albertel 11013: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11014: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11015: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11016: #return $env{$cache_str}='';
1.601 albertel 11017: #}
11018: #$syval.=$1;
11019: #}
1.37 www 11020: } else {
11021: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11022: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11023: &GDBM_READER(),0640)) {
1.37 www 11024: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11025: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11026: unless ($ids) {
11027: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11028: }
11029: unless ($ids) {
11030: # alias?
11031: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11032: }
1.37 www 11033: if ($ids) {
11034: # ------------------------------------------------------------------- Has ID(s)
11035: my @possibilities=split(/\,/,$ids);
1.39 www 11036: if ($#possibilities==0) {
11037: # ----------------------------------------------- There is only one possibility
1.37 www 11038: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11039: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11040: $resid,$thisfn);
1.249 www 11041: } elsif (!$donotrecurse) {
1.39 www 11042: # ------------------------------------------ There is more than one possibility
11043: my $realpossible=0;
1.800 albertel 11044: foreach my $id (@possibilities) {
11045: my $file=$bighash{'src_'.$id};
1.39 www 11046: if (&allowed('bre',$file)) {
1.800 albertel 11047: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11048: if ($bighash{'map_type_'.$mapid} ne 'page') {
11049: $realpossible++;
1.626 albertel 11050: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11051: $resid,$thisfn);
1.39 www 11052: }
11053: }
1.191 harris41 11054: }
1.39 www 11055: if ($realpossible!=1) { $syval=''; }
1.249 www 11056: } else {
11057: $syval='';
1.37 www 11058: }
11059: }
11060: untie(%bighash)
1.481 raeburn 11061: }
1.31 www 11062: }
1.62 www 11063: if ($syval) {
1.620 albertel 11064: return $env{$cache_str}=$syval;
1.62 www 11065: }
1.31 www 11066: }
1.949 raeburn 11067: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11068: return $env{$cache_str}='';
1.31 www 11069: }
11070:
11071: # ---------------------------------------------------------- Return random seed
11072:
1.32 www 11073: sub numval {
11074: my $txt=shift;
11075: $txt=~tr/A-J/0-9/;
11076: $txt=~tr/a-j/0-9/;
11077: $txt=~tr/K-T/0-9/;
11078: $txt=~tr/k-t/0-9/;
11079: $txt=~tr/U-Z/0-5/;
11080: $txt=~tr/u-z/0-5/;
11081: $txt=~s/\D//g;
1.564 albertel 11082: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11083: return int($txt);
1.368 albertel 11084: }
11085:
1.484 albertel 11086: sub numval2 {
11087: my $txt=shift;
11088: $txt=~tr/A-J/0-9/;
11089: $txt=~tr/a-j/0-9/;
11090: $txt=~tr/K-T/0-9/;
11091: $txt=~tr/k-t/0-9/;
11092: $txt=~tr/U-Z/0-5/;
11093: $txt=~tr/u-z/0-5/;
11094: $txt=~s/\D//g;
11095: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11096: my $total;
11097: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11098: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11099: return int($total);
11100: }
11101:
1.575 albertel 11102: sub numval3 {
11103: use integer;
11104: my $txt=shift;
11105: $txt=~tr/A-J/0-9/;
11106: $txt=~tr/a-j/0-9/;
11107: $txt=~tr/K-T/0-9/;
11108: $txt=~tr/k-t/0-9/;
11109: $txt=~tr/U-Z/0-5/;
11110: $txt=~tr/u-z/0-5/;
11111: $txt=~s/\D//g;
11112: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11113: my $total;
11114: foreach my $val (@txts) { $total+=$val; }
11115: if ($_64bit) { $total=(($total<<32)>>32); }
11116: return $total;
11117: }
11118:
1.675 albertel 11119: sub digest {
11120: my ($data)=@_;
11121: my $digest=&Digest::MD5::md5($data);
11122: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11123: my ($e,$f);
11124: {
11125: use integer;
11126: $e=($a+$b);
11127: $f=($c+$d);
11128: if ($_64bit) {
11129: $e=(($e<<32)>>32);
11130: $f=(($f<<32)>>32);
11131: }
11132: }
11133: if (wantarray) {
11134: return ($e,$f);
11135: } else {
11136: my $g;
11137: {
11138: use integer;
11139: $g=($e+$f);
11140: if ($_64bit) {
11141: $g=(($g<<32)>>32);
11142: }
11143: }
11144: return $g;
11145: }
11146: }
11147:
1.368 albertel 11148: sub latest_rnd_algorithm_id {
1.675 albertel 11149: return '64bit5';
1.366 albertel 11150: }
1.32 www 11151:
1.503 albertel 11152: sub get_rand_alg {
11153: my ($courseid)=@_;
1.790 albertel 11154: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11155: if ($courseid) {
1.620 albertel 11156: return $env{"course.$courseid.rndseed"};
1.503 albertel 11157: }
11158: return &latest_rnd_algorithm_id();
11159: }
11160:
1.562 albertel 11161: sub validCODE {
11162: my ($CODE)=@_;
11163: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11164: return 0;
11165: }
11166:
1.491 albertel 11167: sub getCODE {
1.620 albertel 11168: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11169: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11170: defined($Apache::lonhomework::parsing_a_task) ) &&
11171: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11172: return $Apache::lonhomework::history{'resource.CODE'};
11173: }
11174: return undef;
11175: }
1.1133 foxr 11176: #
11177: # Determines the random seed for a specific context:
11178: #
11179: # parameters:
11180: # symb - in course context the symb for the seed.
11181: # course_id - The course id of the form domain_coursenum.
11182: # domain - Domain for the user.
11183: # course - Course for the user.
11184: # cenv - environment of the course.
11185: #
11186: # NOTE:
11187: # All parameters are picked out of the environment if missing
11188: # or not defined.
11189: # If a symb cannot be determined the current time is used instead.
11190: #
11191: # For a given well defined symb, courside, domain, username,
11192: # and course environment, the seed is reproducible.
11193: #
1.31 www 11194: sub rndseed {
1.1133 foxr 11195: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11196: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11197: if (!defined($symb)) {
1.366 albertel 11198: unless ($symb=$wsymb) { return time; }
11199: }
1.1146 foxr 11200: if (!defined $courseid) {
11201: $courseid=$wcourseid;
11202: }
11203: if (!defined $domain) { $domain=$wdomain; }
11204: if (!defined $username) { $username=$wusername }
1.1133 foxr 11205:
11206: my $which;
11207: if (defined($cenv->{'rndseed'})) {
11208: $which = $cenv->{'rndseed'};
11209: } else {
11210: $which =&get_rand_alg($courseid);
11211: }
1.491 albertel 11212: if (defined(&getCODE())) {
1.675 albertel 11213: if ($which eq '64bit5') {
11214: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11215: } elsif ($which eq '64bit4') {
1.575 albertel 11216: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11217: } else {
11218: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11219: }
1.675 albertel 11220: } elsif ($which eq '64bit5') {
11221: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11222: } elsif ($which eq '64bit4') {
11223: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11224: } elsif ($which eq '64bit3') {
11225: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11226: } elsif ($which eq '64bit2') {
11227: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11228: } elsif ($which eq '64bit') {
11229: return &rndseed_64bit($symb,$courseid,$domain,$username);
11230: }
11231: return &rndseed_32bit($symb,$courseid,$domain,$username);
11232: }
11233:
11234: sub rndseed_32bit {
11235: my ($symb,$courseid,$domain,$username)=@_;
11236: {
11237: use integer;
11238: my $symbchck=unpack("%32C*",$symb) << 27;
11239: my $symbseed=numval($symb) << 22;
11240: my $namechck=unpack("%32C*",$username) << 17;
11241: my $nameseed=numval($username) << 12;
11242: my $domainseed=unpack("%32C*",$domain) << 7;
11243: my $courseseed=unpack("%32C*",$courseid);
11244: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11245: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11246: #&logthis("rndseed :$num:$symb");
1.564 albertel 11247: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11248: return $num;
11249: }
11250: }
11251:
11252: sub rndseed_64bit {
11253: my ($symb,$courseid,$domain,$username)=@_;
11254: {
11255: use integer;
11256: my $symbchck=unpack("%32S*",$symb) << 21;
11257: my $symbseed=numval($symb) << 10;
11258: my $namechck=unpack("%32S*",$username);
11259:
11260: my $nameseed=numval($username) << 21;
11261: my $domainseed=unpack("%32S*",$domain) << 10;
11262: my $courseseed=unpack("%32S*",$courseid);
11263:
11264: my $num1=$symbchck+$symbseed+$namechck;
11265: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11266: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11267: #&logthis("rndseed :$num:$symb");
1.564 albertel 11268: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11269: return "$num1,$num2";
1.155 albertel 11270: }
1.366 albertel 11271: }
11272:
1.443 albertel 11273: sub rndseed_64bit2 {
11274: my ($symb,$courseid,$domain,$username)=@_;
11275: {
11276: use integer;
11277: # strings need to be an even # of cahracters long, it it is odd the
11278: # last characters gets thrown away
11279: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11280: my $symbseed=numval($symb) << 10;
11281: my $namechck=unpack("%32S*",$username.' ');
11282:
11283: my $nameseed=numval($username) << 21;
1.501 albertel 11284: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11285: my $courseseed=unpack("%32S*",$courseid.' ');
11286:
11287: my $num1=$symbchck+$symbseed+$namechck;
11288: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11289: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11290: #&logthis("rndseed :$num:$symb");
1.803 albertel 11291: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11292: return "$num1,$num2";
11293: }
11294: }
11295:
11296: sub rndseed_64bit3 {
11297: my ($symb,$courseid,$domain,$username)=@_;
11298: {
11299: use integer;
11300: # strings need to be an even # of cahracters long, it it is odd the
11301: # last characters gets thrown away
11302: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11303: my $symbseed=numval2($symb) << 10;
11304: my $namechck=unpack("%32S*",$username.' ');
11305:
11306: my $nameseed=numval2($username) << 21;
1.443 albertel 11307: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11308: my $courseseed=unpack("%32S*",$courseid.' ');
11309:
11310: my $num1=$symbchck+$symbseed+$namechck;
11311: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11312: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11313: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11314: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11315:
1.503 albertel 11316: return "$num1:$num2";
1.443 albertel 11317: }
11318: }
11319:
1.575 albertel 11320: sub rndseed_64bit4 {
11321: my ($symb,$courseid,$domain,$username)=@_;
11322: {
11323: use integer;
11324: # strings need to be an even # of cahracters long, it it is odd the
11325: # last characters gets thrown away
11326: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11327: my $symbseed=numval3($symb) << 10;
11328: my $namechck=unpack("%32S*",$username.' ');
11329:
11330: my $nameseed=numval3($username) << 21;
11331: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11332: my $courseseed=unpack("%32S*",$courseid.' ');
11333:
11334: my $num1=$symbchck+$symbseed+$namechck;
11335: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11336: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11337: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11338: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11339:
1.575 albertel 11340: return "$num1:$num2";
11341: }
11342: }
11343:
1.675 albertel 11344: sub rndseed_64bit5 {
11345: my ($symb,$courseid,$domain,$username)=@_;
11346: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11347: return "$num1:$num2";
11348: }
11349:
1.366 albertel 11350: sub rndseed_CODE_64bit {
11351: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11352: {
1.366 albertel 11353: use integer;
1.443 albertel 11354: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11355: my $symbseed=numval2($symb);
1.491 albertel 11356: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11357: my $CODEseed=numval(&getCODE());
1.443 albertel 11358: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11359: my $num1=$symbseed+$CODEchck;
11360: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11361: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11362: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11363: if ($_64bit) { $num1=(($num1<<32)>>32); }
11364: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11365: return "$num1:$num2";
1.366 albertel 11366: }
11367: }
11368:
1.575 albertel 11369: sub rndseed_CODE_64bit4 {
11370: my ($symb,$courseid,$domain,$username)=@_;
11371: {
11372: use integer;
11373: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11374: my $symbseed=numval3($symb);
11375: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11376: my $CODEseed=numval3(&getCODE());
11377: my $courseseed=unpack("%32S*",$courseid.' ');
11378: my $num1=$symbseed+$CODEchck;
11379: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11380: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11381: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11382: if ($_64bit) { $num1=(($num1<<32)>>32); }
11383: if ($_64bit) { $num2=(($num2<<32)>>32); }
11384: return "$num1:$num2";
11385: }
11386: }
11387:
1.675 albertel 11388: sub rndseed_CODE_64bit5 {
11389: my ($symb,$courseid,$domain,$username)=@_;
11390: my $code = &getCODE();
11391: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11392: return "$num1:$num2";
11393: }
11394:
1.366 albertel 11395: sub setup_random_from_rndseed {
11396: my ($rndseed)=@_;
1.503 albertel 11397: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11398: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11399: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11400: &Math::Random::random_set_seed_from_phrase($rndseed);
11401: } else {
11402: &Math::Random::random_set_seed($num1,$num2);
11403: }
1.366 albertel 11404: } else {
11405: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11406: }
1.36 albertel 11407: }
11408:
1.474 albertel 11409: sub latest_receipt_algorithm_id {
1.835 albertel 11410: return 'receipt3';
1.474 albertel 11411: }
11412:
1.480 www 11413: sub recunique {
11414: my $fucourseid=shift;
11415: my $unique;
1.835 albertel 11416: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11417: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11418: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11419: } else {
11420: $unique=$perlvar{'lonReceipt'};
11421: }
11422: return unpack("%32C*",$unique);
11423: }
11424:
11425: sub recprefix {
11426: my $fucourseid=shift;
11427: my $prefix;
1.835 albertel 11428: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11429: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11430: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11431: } else {
11432: $prefix=$perlvar{'lonHostID'};
11433: }
11434: return unpack("%32C*",$prefix);
11435: }
11436:
1.76 www 11437: sub ireceipt {
1.474 albertel 11438: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11439:
11440: my $return =&recprefix($fucourseid).'-';
11441:
11442: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11443: $env{'request.state'} eq 'construct') {
11444: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11445: return $return;
11446: }
11447:
1.76 www 11448: my $cuname=unpack("%32C*",$funame);
11449: my $cudom=unpack("%32C*",$fudom);
11450: my $cucourseid=unpack("%32C*",$fucourseid);
11451: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11452: my $cunique=&recunique($fucourseid);
1.474 albertel 11453: my $cpart=unpack("%32S*",$part);
1.835 albertel 11454: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11455:
1.790 albertel 11456: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11457:
11458: $return.= ($cunique%$cuname+
11459: $cunique%$cudom+
11460: $cusymb%$cuname+
11461: $cusymb%$cudom+
11462: $cucourseid%$cuname+
11463: $cucourseid%$cudom+
11464: $cpart%$cuname+
11465: $cpart%$cudom);
11466: } else {
11467: $return.= ($cunique%$cuname+
11468: $cunique%$cudom+
11469: $cusymb%$cuname+
11470: $cusymb%$cudom+
11471: $cucourseid%$cuname+
11472: $cucourseid%$cudom);
11473: }
11474: return $return;
1.76 www 11475: }
11476:
11477: sub receipt {
1.474 albertel 11478: my ($part)=@_;
1.790 albertel 11479: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11480: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11481: }
1.260 ng 11482:
1.790 albertel 11483: sub whichuser {
11484: my ($passedsymb)=@_;
11485: my ($symb,$courseid,$domain,$name,$publicuser);
11486: if (defined($env{'form.grade_symb'})) {
11487: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11488: my $allowed=&allowed('vgr',$tmp_courseid);
11489: if (!$allowed &&
11490: exists($env{'request.course.sec'}) &&
11491: $env{'request.course.sec'} !~ /^\s*$/) {
11492: $allowed=&allowed('vgr',$tmp_courseid.
11493: '/'.$env{'request.course.sec'});
11494: }
11495: if ($allowed) {
11496: ($symb)=&get_env_multiple('form.grade_symb');
11497: $courseid=$tmp_courseid;
11498: ($domain)=&get_env_multiple('form.grade_domain');
11499: ($name)=&get_env_multiple('form.grade_username');
11500: return ($symb,$courseid,$domain,$name,$publicuser);
11501: }
11502: }
11503: if (!$passedsymb) {
11504: $symb=&symbread();
11505: } else {
11506: $symb=$passedsymb;
11507: }
11508: $courseid=$env{'request.course.id'};
11509: $domain=$env{'user.domain'};
11510: $name=$env{'user.name'};
11511: if ($name eq 'public' && $domain eq 'public') {
11512: if (!defined($env{'form.username'})) {
11513: $env{'form.username'}.=time.rand(10000000);
11514: }
11515: $name.=$env{'form.username'};
11516: }
11517: return ($symb,$courseid,$domain,$name,$publicuser);
11518:
11519: }
11520:
1.36 albertel 11521: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11522: # returns either the contents of the file or
11523: # -1 if the file doesn't exist
1.481 raeburn 11524: #
11525: # if the target is a file that was uploaded via DOCS,
11526: # a check will be made to see if a current copy exists on the local server,
11527: # if it does this will be served, otherwise a copy will be retrieved from
11528: # the home server for the course and stored in /home/httpd/html/userfiles on
11529: # the local server.
1.472 albertel 11530:
1.36 albertel 11531: sub getfile {
1.538 albertel 11532: my ($file) = @_;
1.609 banghart 11533: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11534: &repcopy($file);
11535: return &readfile($file);
11536: }
11537:
11538: sub repcopy_userfile {
11539: my ($file)=@_;
1.1142 raeburn 11540: my $londocroot = $perlvar{'lonDocRoot'};
11541: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11542: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11543: my ($cdom,$cnum,$filename) =
1.811 albertel 11544: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11545: my $uri="/uploaded/$cdom/$cnum/$filename";
11546: if (-e "$file") {
1.828 www 11547: # we already have a local copy, check it out
1.538 albertel 11548: my @fileinfo = stat($file);
1.828 www 11549: my $rtncode;
11550: my $info;
1.538 albertel 11551: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11552: if ($lwpresp ne 'ok') {
1.828 www 11553: # there is no such file anymore, even though we had a local copy
1.482 albertel 11554: if ($rtncode eq '404') {
1.538 albertel 11555: unlink($file);
1.482 albertel 11556: }
11557: return -1;
11558: }
11559: if ($info < $fileinfo[9]) {
1.828 www 11560: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11561: return 'ok';
1.828 www 11562: } else {
11563: # the file is outdated, get rid of it
11564: unlink($file);
1.482 albertel 11565: }
1.828 www 11566: }
11567: # one way or the other, at this point, we don't have the file
11568: # construct the correct path for the file
11569: my @parts = ($cdom,$cnum);
11570: if ($filename =~ m|^(.+)/[^/]+$|) {
11571: push @parts, split(/\//,$1);
11572: }
11573: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11574: foreach my $part (@parts) {
11575: $path .= '/'.$part;
11576: if (!-e $path) {
11577: mkdir($path,0770);
1.482 albertel 11578: }
11579: }
1.828 www 11580: # now the path exists for sure
11581: # get a user agent
11582: my $ua=new LWP::UserAgent;
11583: my $transferfile=$file.'.in.transfer';
11584: # FIXME: this should flock
11585: if (-e $transferfile) { return 'ok'; }
11586: my $request;
11587: $uri=~s/^\///;
1.980 raeburn 11588: my $homeserver = &homeserver($cnum,$cdom);
11589: my $protocol = $protocol{$homeserver};
11590: $protocol = 'http' if ($protocol ne 'https');
11591: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11592: my $response=$ua->request($request,$transferfile);
11593: # did it work?
11594: if ($response->is_error()) {
11595: unlink($transferfile);
11596: &logthis("Userfile repcopy failed for $uri");
11597: return -1;
11598: }
11599: # worked, rename the transfer file
11600: rename($transferfile,$file);
1.607 raeburn 11601: return 'ok';
1.481 raeburn 11602: }
11603:
1.517 albertel 11604: sub tokenwrapper {
11605: my $uri=shift;
1.980 raeburn 11606: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11607: $uri=~s|^/||;
1.620 albertel 11608: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11609: my $token=$1;
1.552 albertel 11610: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11611: if ($udom && $uname && $file) {
11612: $file=~s|(\?\.*)*$||;
1.949 raeburn 11613: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11614: my $homeserver = &homeserver($uname,$udom);
11615: my $protocol = $protocol{$homeserver};
11616: $protocol = 'http' if ($protocol ne 'https');
11617: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11618: (($uri=~/\?/)?'&':'?').'token='.$token.
11619: '&tokenissued='.$perlvar{'lonHostID'};
11620: } else {
11621: return '/adm/notfound.html';
11622: }
11623: }
11624:
1.828 www 11625: # call with reqtype HEAD: get last modification time
11626: # call with reqtype GET: get the file contents
11627: # Do not call this with reqtype GET for large files! It loads everything into memory
11628: #
1.481 raeburn 11629: sub getuploaded {
11630: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11631: $uri=~s/^\///;
1.980 raeburn 11632: my $homeserver = &homeserver($cnum,$cdom);
11633: my $protocol = $protocol{$homeserver};
11634: $protocol = 'http' if ($protocol ne 'https');
11635: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11636: my $ua=new LWP::UserAgent;
11637: my $request=new HTTP::Request($reqtype,$uri);
11638: my $response=$ua->request($request);
11639: $$rtncode = $response->code;
1.482 albertel 11640: if (! $response->is_success()) {
11641: return 'failed';
11642: }
11643: if ($reqtype eq 'HEAD') {
1.486 www 11644: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11645: } elsif ($reqtype eq 'GET') {
11646: $$info = $response->content;
1.472 albertel 11647: }
1.482 albertel 11648: return 'ok';
1.36 albertel 11649: }
11650:
1.481 raeburn 11651: sub readfile {
11652: my $file = shift;
11653: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11654: my $fh;
11655: open($fh,"<$file");
11656: my $a='';
1.800 albertel 11657: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11658: return $a;
11659: }
11660:
1.36 albertel 11661: sub filelocation {
1.590 banghart 11662: my ($dir,$file) = @_;
11663: my $location;
11664: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11665:
11666: if ($file =~ m-^/adm/-) {
11667: $file=~s-^/adm/wrapper/-/-;
11668: $file=~s-^/adm/coursedocs/showdoc/-/-;
11669: }
1.882 albertel 11670:
1.1139 www 11671: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11672: $location = $file;
1.609 banghart 11673: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11674: my ($udom,$uname,$filename)=
1.811 albertel 11675: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11676: my $home=&homeserver($uname,$udom);
11677: my $is_me=0;
11678: my @ids=¤t_machine_ids();
11679: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11680: if ($is_me) {
1.1117 foxr 11681: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11682: } else {
11683: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11684: $udom.'/'.$uname.'/'.$filename;
11685: }
1.882 albertel 11686: } elsif ($file =~ m-^/adm/-) {
11687: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11688: } else {
11689: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11690: $file=~s:^/(res|priv)/:/:;
11691: my $space=$1;
1.590 banghart 11692: if ( !( $file =~ m:^/:) ) {
11693: $location = $dir. '/'.$file;
11694: } else {
1.1142 raeburn 11695: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11696: }
1.59 albertel 11697: }
1.590 banghart 11698: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11699: while ($location=~m{/\.\./}) {
11700: if ($location =~ m{/[^/]+/\.\./}) {
11701: $location=~ s{/[^/]+/\.\./}{/}g;
11702: } else {
11703: $location=~ s{/\.\./}{/}g;
11704: }
11705: } #remove dir/..
1.590 banghart 11706: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11707: return $location;
1.46 www 11708: }
1.36 albertel 11709:
1.46 www 11710: sub hreflocation {
11711: my ($dir,$file)=@_;
1.980 raeburn 11712: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11713: $file=filelocation($dir,$file);
1.700 albertel 11714: } elsif ($file=~m-^/adm/-) {
11715: $file=~s-^/adm/wrapper/-/-;
11716: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11717: }
11718: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11719: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11720: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11721: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11722: {/uploaded/$1/$2/}x;
1.46 www 11723: }
1.913 albertel 11724: if ($file=~ m{^/userfiles/}) {
11725: $file =~ s{^/userfiles/}{/uploaded/};
11726: }
1.462 albertel 11727: return $file;
1.465 albertel 11728: }
11729:
1.1139 www 11730:
11731:
11732:
11733:
1.465 albertel 11734: sub current_machine_domains {
1.853 albertel 11735: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11736: }
11737:
11738: sub machine_domains {
11739: my ($hostname) = @_;
1.465 albertel 11740: my @domains;
1.838 albertel 11741: my %hostname = &all_hostnames();
1.465 albertel 11742: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11743: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11744: if ($hostname eq $name) {
1.844 albertel 11745: push(@domains,&host_domain($id));
1.465 albertel 11746: }
11747: }
11748: return @domains;
11749: }
11750:
11751: sub current_machine_ids {
1.853 albertel 11752: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11753: }
11754:
11755: sub machine_ids {
11756: my ($hostname) = @_;
11757: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11758: my @ids;
1.888 albertel 11759: my %name_to_host = &all_names();
1.889 albertel 11760: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11761: return @{ $name_to_host{$hostname} };
11762: }
11763: return;
1.31 www 11764: }
11765:
1.824 raeburn 11766: sub additional_machine_domains {
11767: my @domains;
11768: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11769: while( my $line = <$fh>) {
11770: $line =~ s/\s//g;
11771: push(@domains,$line);
11772: }
11773: return @domains;
11774: }
11775:
11776: sub default_login_domain {
11777: my $domain = $perlvar{'lonDefDomain'};
11778: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11779: foreach my $posdom (¤t_machine_domains(),
11780: &additional_machine_domains()) {
11781: if (lc($posdom) eq lc($testdomain)) {
11782: $domain=$posdom;
11783: last;
11784: }
11785: }
11786: return $domain;
11787: }
11788:
1.31 www 11789: # ------------------------------------------------------------- Declutters URLs
11790:
11791: sub declutter {
11792: my $thisfn=shift;
1.569 albertel 11793: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 11794: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11795: $thisfn=~s{^/home/httpd/html}{};
11796: }
1.31 www 11797: $thisfn=~s/^\///;
1.697 albertel 11798: $thisfn=~s|^adm/wrapper/||;
11799: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11800: $thisfn=~s/^res\///;
1.1172 bisitz 11801: $thisfn=~s/^priv\///;
1.1032 raeburn 11802: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11803: $thisfn=~s/\?.+$//;
11804: }
1.268 www 11805: return $thisfn;
11806: }
11807:
11808: # ------------------------------------------------------------- Clutter up URLs
11809:
11810: sub clutter {
11811: my $thisfn='/'.&declutter(shift);
1.887 albertel 11812: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11813: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11814: $thisfn='/res'.$thisfn;
11815: }
1.1031 raeburn 11816: if ($thisfn !~m|^/adm|) {
11817: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11818: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11819: } else {
11820: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11821: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11822: if ($embstyle eq 'ssi'
11823: || ($embstyle eq 'hdn')
11824: || ($embstyle eq 'rat')
11825: || ($embstyle eq 'prv')
11826: || ($embstyle eq 'ign')) {
11827: #do nothing with these
11828: } elsif (($embstyle eq 'img')
1.695 albertel 11829: || ($embstyle eq 'emb')
11830: || ($embstyle eq 'wrp')) {
11831: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11832: } elsif ($embstyle eq 'unk'
11833: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11834: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11835: } else {
1.718 www 11836: # &logthis("Got a blank emb style");
1.695 albertel 11837: }
1.694 albertel 11838: }
11839: }
1.31 www 11840: return $thisfn;
1.12 www 11841: }
11842:
1.787 albertel 11843: sub clutter_with_no_wrapper {
11844: my $uri = &clutter(shift);
11845: if ($uri =~ m-^/adm/-) {
11846: $uri =~ s-^/adm/wrapper/-/-;
11847: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11848: }
11849: return $uri;
11850: }
11851:
1.557 albertel 11852: sub freeze_escape {
11853: my ($value)=@_;
11854: if (ref($value)) {
11855: $value=&nfreeze($value);
11856: return '__FROZEN__'.&escape($value);
11857: }
11858: return &escape($value);
11859: }
11860:
1.11 www 11861:
1.557 albertel 11862: sub thaw_unescape {
11863: my ($value)=@_;
11864: if ($value =~ /^__FROZEN__/) {
11865: substr($value,0,10,undef);
11866: $value=&unescape($value);
11867: return &thaw($value);
11868: }
11869: return &unescape($value);
11870: }
11871:
1.436 albertel 11872: sub correct_line_ends {
11873: my ($result)=@_;
11874: $$result =~s/\r\n/\n/mg;
11875: $$result =~s/\r/\n/mg;
1.415 albertel 11876: }
1.1 albertel 11877: # ================================================================ Main Program
11878:
1.184 www 11879: sub goodbye {
1.204 albertel 11880: &logthis("Starting Shut down");
1.443 albertel 11881: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11882: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11883: #converted
1.599 albertel 11884: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11885: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11886: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11887: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11888: #1.1 only
1.870 albertel 11889: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11890: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11891: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11892: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11893: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11894: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11895: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11896: &flushcourselogs();
11897: &logthis("Shutting down");
11898: }
11899:
1.852 albertel 11900: sub get_dns {
1.1172.2.17 raeburn 11901: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11902: if (!$ignore_cache) {
11903: my ($content,$cached)=
11904: &Apache::lonnet::is_cached_new('dns',$url);
11905: if ($cached) {
1.1172.2.17 raeburn 11906: &$func($content,$hashref);
1.869 albertel 11907: return;
11908: }
11909: }
11910:
11911: my %alldns;
1.852 albertel 11912: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11913: foreach my $dns (<$config>) {
11914: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11915: my $line = $1;
11916: my ($host,$protocol) = split(/:/,$line);
11917: if ($protocol ne 'https') {
11918: $protocol = 'http';
11919: }
11920: $alldns{$host} = $protocol;
1.869 albertel 11921: }
11922: while (%alldns) {
1.1172.2.52 raeburn 11923: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 11924: my $ua=new LWP::UserAgent;
1.1134 raeburn 11925: $ua->timeout(30);
1.979 raeburn 11926: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11927: my $response=$ua->request($request);
1.979 raeburn 11928: delete($alldns{$dns});
1.852 albertel 11929: next if ($response->is_error());
11930: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11931: unless ($nocache) {
1.1172.2.23 raeburn 11932: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11933: }
11934: &$func(\@content,$hashref);
1.869 albertel 11935: return;
1.852 albertel 11936: }
11937: close($config);
1.871 albertel 11938: my $which = (split('/',$url))[3];
11939: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11940: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11941: my @content = <$config>;
1.1172.2.17 raeburn 11942: &$func(\@content,$hashref);
11943: return;
11944: }
11945:
11946: # ------------------------------------------------------Get DNS checksums file
11947: sub parse_dns_checksums_tab {
11948: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 11949: my $lonhost = $perlvar{'lonHostID'};
11950: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 11951: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 11952: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11953: my $webconfdir = '/etc/httpd/conf';
11954: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11955: $webconfdir = '/etc/apache2';
11956: } elsif ($distro =~ /^sles(\d+)$/) {
11957: if ($1 >= 10) {
11958: $webconfdir = '/etc/apache2';
11959: }
11960: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11961: if ($1 >= 10.0) {
11962: $webconfdir = '/etc/apache2';
11963: }
11964: }
1.1172.2.17 raeburn 11965: my ($release,$timestamp) = split(/\-/,$loncaparev);
11966: my (%chksum,%revnum);
11967: if (ref($lines) eq 'ARRAY') {
11968: chomp(@{$lines});
1.1172.2.34 raeburn 11969: my $version = shift(@{$lines});
11970: if ($version eq $release) {
1.1172.2.17 raeburn 11971: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11972: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 11973: if ($file =~ m{^/etc/httpd/conf}) {
11974: if ($webconfdir eq '/etc/apache2') {
11975: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11976: }
11977: }
1.1172.2.34 raeburn 11978: $chksum{$file} = $shasum;
11979: $revnum{$file} = $version;
1.1172.2.17 raeburn 11980: }
11981: if (ref($hashref) eq 'HASH') {
11982: %{$hashref} = (
11983: sums => \%chksum,
11984: versions => \%revnum,
11985: );
11986: }
11987: }
11988: }
1.869 albertel 11989: return;
1.852 albertel 11990: }
1.1172.2.17 raeburn 11991:
11992: sub fetch_dns_checksums {
11993: my %checksums;
1.1172.2.34 raeburn 11994: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 11995: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 11996: my ($release,$timestamp) = split(/\-/,$loncaparev);
11997: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11998: \%checksums);
11999: return \%checksums;
12000: }
12001:
1.327 albertel 12002: # ------------------------------------------------------------ Read domain file
12003: {
1.852 albertel 12004: my $loaded;
1.846 albertel 12005: my %domain;
12006:
1.852 albertel 12007: sub parse_domain_tab {
12008: my ($lines) = @_;
12009: foreach my $line (@$lines) {
12010: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12011:
1.846 albertel 12012: chomp($line);
1.852 albertel 12013: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12014: my %this_domain;
12015: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12016: 'lang_def', 'city', 'longi', 'lati',
12017: 'primary') {
12018: $this_domain{$field} = shift(@elements);
12019: }
12020: $domain{$name} = \%this_domain;
1.852 albertel 12021: }
12022: }
1.864 albertel 12023:
12024: sub reset_domain_info {
12025: undef($loaded);
12026: undef(%domain);
12027: }
12028:
1.852 albertel 12029: sub load_domain_tab {
1.869 albertel 12030: my ($ignore_cache) = @_;
12031: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12032: my $fh;
12033: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12034: my @lines = <$fh>;
12035: &parse_domain_tab(\@lines);
1.448 albertel 12036: }
1.852 albertel 12037: close($fh);
12038: $loaded = 1;
1.327 albertel 12039: }
1.846 albertel 12040:
12041: sub domain {
1.852 albertel 12042: &load_domain_tab() if (!$loaded);
12043:
1.846 albertel 12044: my ($name,$what) = @_;
12045: return if ( !exists($domain{$name}) );
12046:
12047: if (!$what) {
12048: return $domain{$name}{'description'};
12049: }
12050: return $domain{$name}{$what};
12051: }
1.974 raeburn 12052:
12053: sub domain_info {
12054: &load_domain_tab() if (!$loaded);
12055: return %domain;
12056: }
12057:
1.327 albertel 12058: }
12059:
12060:
1.1 albertel 12061: # ------------------------------------------------------------- Read hosts file
12062: {
1.838 albertel 12063: my %hostname;
1.844 albertel 12064: my %hostdom;
1.845 albertel 12065: my %libserv;
1.852 albertel 12066: my $loaded;
1.888 albertel 12067: my %name_to_host;
1.1074 raeburn 12068: my %internetdom;
1.1107 raeburn 12069: my %LC_dns_serv;
1.852 albertel 12070:
12071: sub parse_hosts_tab {
12072: my ($file) = @_;
12073: foreach my $configline (@$file) {
12074: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12075: chomp($configline);
12076: if ($configline =~ /^\^/) {
12077: if ($configline =~ /^\^([\w.\-]+)/) {
12078: $LC_dns_serv{$1} = 1;
12079: }
12080: next;
12081: }
1.1074 raeburn 12082: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12083: $name=~s/\s//g;
12084: if ($id && $domain && $role && $name) {
12085: $hostname{$id}=$name;
1.888 albertel 12086: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12087: $hostdom{$id}=$domain;
12088: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12089: if (defined($protocol)) {
12090: if ($protocol eq 'https') {
12091: $protocol{$id} = $protocol;
12092: } else {
12093: $protocol{$id} = 'http';
12094: }
1.968 raeburn 12095: } else {
1.969 raeburn 12096: $protocol{$id} = 'http';
1.968 raeburn 12097: }
1.1074 raeburn 12098: if (defined($intdom)) {
12099: $internetdom{$id} = $intdom;
12100: }
1.852 albertel 12101: }
12102: }
12103: }
1.864 albertel 12104:
12105: sub reset_hosts_info {
1.897 albertel 12106: &purge_remembered();
1.864 albertel 12107: &reset_domain_info();
12108: &reset_hosts_ip_info();
1.892 albertel 12109: undef(%name_to_host);
1.864 albertel 12110: undef(%hostname);
12111: undef(%hostdom);
12112: undef(%libserv);
12113: undef($loaded);
12114: }
1.1 albertel 12115:
1.852 albertel 12116: sub load_hosts_tab {
1.869 albertel 12117: my ($ignore_cache) = @_;
12118: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12119: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12120: my @config = <$config>;
12121: &parse_hosts_tab(\@config);
12122: close($config);
12123: $loaded=1;
1.1 albertel 12124: }
1.852 albertel 12125:
1.838 albertel 12126: sub hostname {
1.852 albertel 12127: &load_hosts_tab() if (!$loaded);
12128:
1.838 albertel 12129: my ($lonid) = @_;
12130: return $hostname{$lonid};
12131: }
1.845 albertel 12132:
1.838 albertel 12133: sub all_hostnames {
1.852 albertel 12134: &load_hosts_tab() if (!$loaded);
12135:
1.838 albertel 12136: return %hostname;
12137: }
1.845 albertel 12138:
1.888 albertel 12139: sub all_names {
12140: &load_hosts_tab() if (!$loaded);
12141:
12142: return %name_to_host;
12143: }
12144:
1.974 raeburn 12145: sub all_host_domain {
12146: &load_hosts_tab() if (!$loaded);
12147: return %hostdom;
12148: }
12149:
1.845 albertel 12150: sub is_library {
1.852 albertel 12151: &load_hosts_tab() if (!$loaded);
12152:
1.845 albertel 12153: return exists($libserv{$_[0]});
12154: }
12155:
12156: sub all_library {
1.852 albertel 12157: &load_hosts_tab() if (!$loaded);
12158:
1.845 albertel 12159: return %libserv;
12160: }
12161:
1.1062 droeschl 12162: sub unique_library {
12163: #2x reverse removes all hostnames that appear more than once
12164: my %unique = reverse &all_library();
12165: return reverse %unique;
12166: }
12167:
1.841 albertel 12168: sub get_servers {
1.852 albertel 12169: &load_hosts_tab() if (!$loaded);
12170:
1.841 albertel 12171: my ($domain,$type) = @_;
12172: my %possible_hosts = ($type eq 'library') ? %libserv
12173: : %hostname;
12174: my %result;
1.842 albertel 12175: if (ref($domain) eq 'ARRAY') {
12176: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12177: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12178: $result{$host} = $hostname;
12179: }
12180: }
12181: } else {
12182: while ( my ($host,$hostname) = each(%possible_hosts)) {
12183: if ($hostdom{$host} eq $domain) {
12184: $result{$host} = $hostname;
12185: }
1.841 albertel 12186: }
12187: }
12188: return %result;
12189: }
1.845 albertel 12190:
1.1062 droeschl 12191: sub get_unique_servers {
12192: my %unique = reverse &get_servers(@_);
12193: return reverse %unique;
12194: }
12195:
1.844 albertel 12196: sub host_domain {
1.852 albertel 12197: &load_hosts_tab() if (!$loaded);
12198:
1.844 albertel 12199: my ($lonid) = @_;
12200: return $hostdom{$lonid};
12201: }
12202:
1.841 albertel 12203: sub all_domains {
1.852 albertel 12204: &load_hosts_tab() if (!$loaded);
12205:
1.841 albertel 12206: my %seen;
12207: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12208: return @uniq;
12209: }
1.1074 raeburn 12210:
12211: sub internet_dom {
12212: &load_hosts_tab() if (!$loaded);
12213:
12214: my ($lonid) = @_;
12215: return $internetdom{$lonid};
12216: }
1.1107 raeburn 12217:
12218: sub is_LC_dns {
12219: &load_hosts_tab() if (!$loaded);
12220:
12221: my ($hostname) = @_;
12222: return exists($LC_dns_serv{$hostname});
12223: }
12224:
1.1 albertel 12225: }
12226:
1.847 albertel 12227: {
12228: my %iphost;
1.856 albertel 12229: my %name_to_ip;
12230: my %lonid_to_ip;
1.869 albertel 12231:
1.847 albertel 12232: sub get_hosts_from_ip {
12233: my ($ip) = @_;
12234: my %iphosts = &get_iphost();
12235: if (ref($iphosts{$ip})) {
12236: return @{$iphosts{$ip}};
12237: }
12238: return;
1.839 albertel 12239: }
1.864 albertel 12240:
12241: sub reset_hosts_ip_info {
12242: undef(%iphost);
12243: undef(%name_to_ip);
12244: undef(%lonid_to_ip);
12245: }
1.856 albertel 12246:
12247: sub get_host_ip {
12248: my ($lonid) = @_;
12249: if (exists($lonid_to_ip{$lonid})) {
12250: return $lonid_to_ip{$lonid};
12251: }
12252: my $name=&hostname($lonid);
12253: my $ip = gethostbyname($name);
12254: return if (!$ip || length($ip) ne 4);
12255: $ip=inet_ntoa($ip);
12256: $name_to_ip{$name} = $ip;
12257: $lonid_to_ip{$lonid} = $ip;
12258: return $ip;
12259: }
1.847 albertel 12260:
12261: sub get_iphost {
1.869 albertel 12262: my ($ignore_cache) = @_;
1.894 albertel 12263:
1.869 albertel 12264: if (!$ignore_cache) {
12265: if (%iphost) {
12266: return %iphost;
12267: }
12268: my ($ip_info,$cached)=
12269: &Apache::lonnet::is_cached_new('iphost','iphost');
12270: if ($cached) {
12271: %iphost = %{$ip_info->[0]};
12272: %name_to_ip = %{$ip_info->[1]};
12273: %lonid_to_ip = %{$ip_info->[2]};
12274: return %iphost;
12275: }
12276: }
1.894 albertel 12277:
12278: # get yesterday's info for fallback
12279: my %old_name_to_ip;
12280: my ($ip_info,$cached)=
12281: &Apache::lonnet::is_cached_new('iphost','iphost');
12282: if ($cached) {
12283: %old_name_to_ip = %{$ip_info->[1]};
12284: }
12285:
1.888 albertel 12286: my %name_to_host = &all_names();
12287: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12288: my $ip;
12289: if (!exists($name_to_ip{$name})) {
12290: $ip = gethostbyname($name);
12291: if (!$ip || length($ip) ne 4) {
1.894 albertel 12292: if (defined($old_name_to_ip{$name})) {
12293: $ip = $old_name_to_ip{$name};
12294: &logthis("Can't find $name defaulting to old $ip");
12295: } else {
12296: &logthis("Name $name no IP found");
12297: next;
12298: }
12299: } else {
12300: $ip=inet_ntoa($ip);
1.847 albertel 12301: }
12302: $name_to_ip{$name} = $ip;
12303: } else {
12304: $ip = $name_to_ip{$name};
1.653 albertel 12305: }
1.888 albertel 12306: foreach my $id (@{ $name_to_host{$name} }) {
12307: $lonid_to_ip{$id} = $ip;
12308: }
12309: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12310: }
1.1172.2.23 raeburn 12311: &do_cache_new('iphost','iphost',
12312: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12313: 48*60*60);
1.869 albertel 12314:
1.847 albertel 12315: return %iphost;
1.598 albertel 12316: }
12317:
1.992 raeburn 12318: #
12319: # Given a DNS returns the loncapa host name for that DNS
12320: #
12321: sub host_from_dns {
12322: my ($dns) = @_;
12323: my @hosts;
12324: my $ip;
12325:
1.993 raeburn 12326: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12327: $ip = $name_to_ip{$dns};
12328: }
12329: if (!$ip) {
12330: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12331: if (length($ip) == 4) {
12332: $ip = &IO::Socket::inet_ntoa($ip);
12333: }
12334: }
12335: if ($ip) {
12336: @hosts = get_hosts_from_ip($ip);
12337: return $hosts[0];
12338: }
12339: return undef;
1.986 foxr 12340: }
1.992 raeburn 12341:
1.1074 raeburn 12342: sub get_internet_names {
12343: my ($lonid) = @_;
12344: return if ($lonid eq '');
12345: my ($idnref,$cached)=
12346: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12347: if ($cached) {
12348: return $idnref;
12349: }
12350: my $ip = &get_host_ip($lonid);
12351: my @hosts = &get_hosts_from_ip($ip);
12352: my %iphost = &get_iphost();
12353: my (@idns,%seen);
12354: foreach my $id (@hosts) {
12355: my $dom = &host_domain($id);
12356: my $prim_id = &domain($dom,'primary');
12357: my $prim_ip = &get_host_ip($prim_id);
12358: next if ($seen{$prim_ip});
12359: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12360: foreach my $id (@{$iphost{$prim_ip}}) {
12361: my $intdom = &internet_dom($id);
12362: unless (grep(/^\Q$intdom\E$/,@idns)) {
12363: push(@idns,$intdom);
12364: }
12365: }
12366: }
12367: $seen{$prim_ip} = 1;
12368: }
1.1172.2.23 raeburn 12369: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12370: }
12371:
1.986 foxr 12372: }
12373:
1.1079 raeburn 12374: sub all_loncaparevs {
1.1172.2.39 raeburn 12375: 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 12376: }
12377:
1.1172.2.27 raeburn 12378: # ------------------------------------------------------- Read loncaparev table
12379: {
12380: sub load_loncaparevs {
12381: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12382: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12383: while (my $configline=<$config>) {
12384: chomp($configline);
12385: my ($hostid,$loncaparev)=split(/:/,$configline);
12386: $loncaparevs{$hostid}=$loncaparev;
12387: }
12388: close($config);
12389: }
12390: }
12391: }
12392: }
12393:
12394: # ----------------------------------------------------- Read serverhostID table
12395: {
12396: sub load_serverhomeIDs {
12397: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12398: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12399: while (my $configline=<$config>) {
12400: chomp($configline);
12401: my ($name,$id)=split(/:/,$configline);
12402: $serverhomeIDs{$name}=$id;
12403: }
12404: close($config);
12405: }
12406: }
12407: }
12408: }
12409:
12410:
1.862 albertel 12411: BEGIN {
12412:
12413: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12414: unless ($readit) {
12415: {
12416: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12417: %perlvar = (%perlvar,%{$configvars});
12418: }
12419:
12420:
1.1 albertel 12421: # ------------------------------------------------------ Read spare server file
12422: {
1.448 albertel 12423: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12424:
12425: while (my $configline=<$config>) {
12426: chomp($configline);
1.284 matthew 12427: if ($configline) {
1.784 albertel 12428: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12429: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12430: push(@{ $spareid{$type} }, $host);
1.1 albertel 12431: }
12432: }
1.448 albertel 12433: close($config);
1.1 albertel 12434: }
1.11 www 12435: # ------------------------------------------------------------ Read permissions
12436: {
1.448 albertel 12437: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12438:
12439: while (my $configline=<$config>) {
1.448 albertel 12440: chomp($configline);
12441: if ($configline) {
12442: my ($role,$perm)=split(/ /,$configline);
12443: if ($perm ne '') { $pr{$role}=$perm; }
12444: }
1.11 www 12445: }
1.448 albertel 12446: close($config);
1.11 www 12447: }
12448:
12449: # -------------------------------------------- Read plain texts for permissions
12450: {
1.448 albertel 12451: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12452:
12453: while (my $configline=<$config>) {
1.448 albertel 12454: chomp($configline);
12455: if ($configline) {
1.742 raeburn 12456: my ($short,@plain)=split(/:/,$configline);
12457: %{$prp{$short}} = ();
12458: if (@plain > 0) {
12459: $prp{$short}{'std'} = $plain[0];
12460: for (my $i=1; $i<@plain; $i++) {
12461: $prp{$short}{'alt'.$i} = $plain[$i];
12462: }
12463: }
1.448 albertel 12464: }
1.135 www 12465: }
1.448 albertel 12466: close($config);
1.135 www 12467: }
12468:
12469: # ---------------------------------------------------------- Read package table
12470: {
1.448 albertel 12471: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12472:
12473: while (my $configline=<$config>) {
1.483 albertel 12474: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12475: chomp($configline);
12476: my ($short,$plain)=split(/:/,$configline);
12477: my ($pack,$name)=split(/\&/,$short);
12478: if ($plain ne '') {
12479: $packagetab{$pack.'&'.$name.'&name'}=$name;
12480: $packagetab{$short}=$plain;
12481: }
1.11 www 12482: }
1.448 albertel 12483: close($config);
1.329 matthew 12484: }
12485:
1.1172.2.27 raeburn 12486: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12487:
1.1172.2.27 raeburn 12488: &load_loncaparevs();
12489:
12490: # ------------------------------------------------------- Read serverhostID table
12491:
12492: &load_serverhomeIDs();
1.1074 raeburn 12493:
1.1172.2.27 raeburn 12494: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12495: {
12496: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12497: if (-e $file) {
12498: my $parser = HTML::LCParser->new($file);
12499: while (my $token = $parser->get_token()) {
12500: if ($token->[0] eq 'S') {
12501: my $item = $token->[1];
12502: my $name = $token->[2]{'name'};
12503: my $value = $token->[2]{'value'};
12504: if ($item ne '' && $name ne '' && $value ne '') {
12505: my $release = $parser->get_text();
12506: $release =~ s/(^\s*|\s*$ )//gx;
12507: $needsrelease{$item.':'.$name.':'.$value} = $release;
12508: }
12509: }
12510: }
12511: }
1.1073 raeburn 12512: }
12513:
1.1138 raeburn 12514: # ---------------------------------------------------------- Read managers table
12515: {
12516: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12517: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12518: while (my $configline=<$config>) {
12519: chomp($configline);
12520: next if ($configline =~ /^\#/);
12521: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12522: $managerstab{$configline} = 1;
12523: }
12524: }
12525: close($config);
12526: }
12527: }
12528: }
12529:
1.329 matthew 12530: # ------------- set up temporary directory
12531: {
1.1117 foxr 12532: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12533:
1.11 www 12534: }
12535:
1.794 albertel 12536: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12537: 'compress_threshold'=> 20_000,
12538: });
1.185 www 12539:
1.281 www 12540: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12541: $dumpcount=0;
1.958 www 12542: $locknum=0;
1.22 www 12543:
1.163 harris41 12544: &logtouch();
1.672 albertel 12545: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12546: $readit=1;
1.564 albertel 12547: {
12548: use integer;
12549: my $test=(2**32)+1;
1.568 albertel 12550: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12551: &logthis(" Detected 64bit platform ($_64bit)");
12552: }
1.195 www 12553: }
1.1 albertel 12554: }
1.179 www 12555:
1.1 albertel 12556: 1;
1.191 harris41 12557: __END__
12558:
1.243 albertel 12559: =pod
12560:
1.191 harris41 12561: =head1 NAME
12562:
1.243 albertel 12563: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12564:
12565: =head1 SYNOPSIS
12566:
1.243 albertel 12567: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12568:
12569: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12570:
1.243 albertel 12571: Common parameters:
12572:
12573: =over 4
12574:
12575: =item *
12576:
12577: $uname : an internal username (if $cname expecting a course Id specifically)
12578:
12579: =item *
12580:
12581: $udom : a domain (if $cdom expecting a course's domain specifically)
12582:
12583: =item *
12584:
12585: $symb : a resource instance identifier
12586:
12587: =item *
12588:
12589: $namespace : the name of a .db file that contains the data needed or
12590: being set.
12591:
12592: =back
12593:
1.394 bowersj2 12594: =head1 OVERVIEW
1.191 harris41 12595:
1.394 bowersj2 12596: lonnet provides subroutines which interact with the
12597: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12598: about classes, users, and resources.
1.243 albertel 12599:
12600: For many of these objects you can also use this to store data about
12601: them or modify them in various ways.
1.191 harris41 12602:
1.394 bowersj2 12603: =head2 Symbs
1.191 harris41 12604:
1.394 bowersj2 12605: To identify a specific instance of a resource, LON-CAPA uses symbols
12606: or "symbs"X<symb>. These identifiers are built from the URL of the
12607: map, the resource number of the resource in the map, and the URL of
12608: the resource itself. The latter is somewhat redundant, but might help
12609: if maps change.
12610:
12611: An example is
12612:
12613: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12614:
12615: The respective map entry is
12616:
12617: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12618: title="Problem 2">
12619: </resource>
12620:
12621: Symbs are used by the random number generator, as well as to store and
12622: restore data specific to a certain instance of for example a problem.
12623:
12624: =head2 Storing And Retrieving Data
12625:
12626: X<store()>X<cstore()>X<restore()>Three of the most important functions
12627: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12628: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12629: is is the non-critical message twin of cstore. These functions are for
12630: handlers to store a perl hash to a user's permanent data space in an
12631: easy manner, and to retrieve it again on another call. It is expected
12632: that a handler would use this once at the beginning to retrieve data,
12633: and then again once at the end to send only the new data back.
12634:
12635: The data is stored in the user's data directory on the user's
12636: homeserver under the ID of the course.
12637:
12638: The hash that is returned by restore will have all of the previous
12639: value for all of the elements of the hash.
12640:
12641: Example:
12642:
12643: #creating a hash
12644: my %hash;
12645: $hash{'foo'}='bar';
12646:
12647: #storing it
12648: &Apache::lonnet::cstore(\%hash);
12649:
12650: #changing a value
12651: $hash{'foo'}='notbar';
12652:
12653: #adding a new value
12654: $hash{'bar'}='foo';
12655: &Apache::lonnet::cstore(\%hash);
12656:
12657: #retrieving the hash
12658: my %history=&Apache::lonnet::restore();
12659:
12660: #print the hash
12661: foreach my $key (sort(keys(%history))) {
12662: print("\%history{$key} = $history{$key}");
12663: }
12664:
12665: Will print out:
1.191 harris41 12666:
1.394 bowersj2 12667: %history{1:foo} = bar
12668: %history{1:keys} = foo:timestamp
12669: %history{1:timestamp} = 990455579
12670: %history{2:bar} = foo
12671: %history{2:foo} = notbar
12672: %history{2:keys} = foo:bar:timestamp
12673: %history{2:timestamp} = 990455580
12674: %history{bar} = foo
12675: %history{foo} = notbar
12676: %history{timestamp} = 990455580
12677: %history{version} = 2
12678:
12679: Note that the special hash entries C<keys>, C<version> and
12680: C<timestamp> were added to the hash. C<version> will be equal to the
12681: total number of versions of the data that have been stored. The
12682: C<timestamp> attribute will be the UNIX time the hash was
12683: stored. C<keys> is available in every historical section to list which
12684: keys were added or changed at a specific historical revision of a
12685: hash.
12686:
12687: B<Warning>: do not store the hash that restore returns directly. This
12688: will cause a mess since it will restore the historical keys as if the
12689: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12690:
1.394 bowersj2 12691: Calling convention:
1.191 harris41 12692:
1.1172.2.27 raeburn 12693: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12694: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12695:
1.394 bowersj2 12696: For more detailed information, see lonnet specific documentation.
1.191 harris41 12697:
1.394 bowersj2 12698: =head1 RETURN MESSAGES
1.191 harris41 12699:
1.394 bowersj2 12700: =over 4
1.191 harris41 12701:
1.394 bowersj2 12702: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12703:
1.394 bowersj2 12704: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12705: when the connection is brought back up
1.191 harris41 12706:
1.394 bowersj2 12707: =item * B<con_failed>: unable to contact remote host and unable to save message
12708: for later delivery
1.191 harris41 12709:
1.967 bisitz 12710: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12711:
1.394 bowersj2 12712: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12713: that was requested
1.191 harris41 12714:
1.243 albertel 12715: =back
1.191 harris41 12716:
1.243 albertel 12717: =head1 PUBLIC SUBROUTINES
1.191 harris41 12718:
1.243 albertel 12719: =head2 Session Environment Functions
1.191 harris41 12720:
1.243 albertel 12721: =over 4
1.191 harris41 12722:
1.394 bowersj2 12723: =item *
12724: X<appenv()>
1.949 raeburn 12725: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12726: the user envirnoment file, and will be restored for each access this
1.620 albertel 12727: user makes during this session, also modifies the %env for the current
1.949 raeburn 12728: process. Optional rolesarrayref - if defined contains a reference to an array
12729: of roles which are exempt from the restriction on modifying user.role entries
12730: in the user's environment.db and in %env.
1.191 harris41 12731:
12732: =item *
1.394 bowersj2 12733: X<delenv()>
1.987 raeburn 12734: B<delenv($delthis,$regexp)>: removes all items from the session
12735: environment file that begin with $delthis. If the
12736: optional second arg - $regexp - is true, $delthis is treated as a
12737: regular expression, otherwise \Q$delthis\E is used.
12738: The values are also deleted from the current processes %env.
1.191 harris41 12739:
1.795 albertel 12740: =item * get_env_multiple($name)
12741:
12742: gets $name from the %env hash, it seemlessly handles the cases where multiple
12743: values may be defined and end up as an array ref.
12744:
12745: returns an array of values
12746:
1.243 albertel 12747: =back
12748:
12749: =head2 User Information
1.191 harris41 12750:
1.243 albertel 12751: =over 4
1.191 harris41 12752:
12753: =item *
1.394 bowersj2 12754: X<queryauthenticate()>
12755: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12756: authentication scheme
12757:
12758: =item *
1.394 bowersj2 12759: X<authenticate()>
1.1073 raeburn 12760: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12761: authenticate user from domain's lib servers (first use the current
12762: one). C<$upass> should be the users password.
1.1073 raeburn 12763: $checkdefauth is optional (value is 1 if a check should be made to
12764: authenticate user using default authentication method, and allow
12765: account creation if username does not have account in the domain).
12766: $clientcancheckhost is optional (value is 1 if checking whether the
12767: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12768:
12769: =item *
1.394 bowersj2 12770: X<homeserver()>
12771: B<homeserver($uname,$udom)>: find the server which has
12772: the user's directory and files (there must be only one), this caches
12773: the answer, and also caches if there is a borken connection.
1.191 harris41 12774:
12775: =item *
1.394 bowersj2 12776: X<idget()>
12777: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12778: (IDs are a unique resource in a domain, there must be only 1 ID per
12779: username, and only 1 username per ID in a specific domain) (returns
12780: hash: id=>name,id=>name)
1.191 harris41 12781:
12782: =item *
1.394 bowersj2 12783: X<idrget()>
12784: B<idrget($udom,@unames)>: find the IDs behind a list of
12785: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12786:
12787: =item *
1.394 bowersj2 12788: X<idput()>
12789: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12790:
12791: =item *
1.394 bowersj2 12792: X<rolesinit()>
1.1169 droeschl 12793: B<rolesinit($udom,$username)>: get user privileges.
12794: returns user role, first access and timer interval hashes
1.243 albertel 12795:
12796: =item *
1.1171 droeschl 12797: X<privileged()>
12798: B<privileged($username,$domain)>: returns a true if user has a
12799: privileged and active role (i.e. su or dc), false otherwise.
12800:
12801: =item *
1.551 albertel 12802: X<getsection()>
12803: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12804: course $cname, return section name/number or '' for "not in course"
12805: and '-1' for "no section"
12806:
12807: =item *
1.394 bowersj2 12808: X<userenvironment()>
12809: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12810: passed in @what from the requested user's environment, returns a hash
12811:
1.858 raeburn 12812: =item *
12813: X<userlog_query()>
1.859 albertel 12814: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12815: activity.log file. %filters defines filters applied when parsing the
12816: log file. These can be start or end timestamps, or the type of action
12817: - log to look for Login or Logout events, check for Checkin or
12818: Checkout, role for role selection. The response is in the form
12819: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12820: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12821:
1.243 albertel 12822: =back
12823:
12824: =head2 User Roles
12825:
12826: =over 4
12827:
12828: =item *
12829:
1.810 raeburn 12830: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12831: F: full access
12832: U,I,K: authentication modes (cxx only)
12833: '': forbidden
12834: 1: user needs to choose course
12835: 2: browse allowed
1.766 albertel 12836: A: passphrase authentication needed
1.243 albertel 12837:
12838: =item *
12839:
1.1172.2.13 raeburn 12840: constructaccess($url,$setpriv) : check for access to construction space URL
12841:
12842: See if the owner domain and name in the URL match those in the
12843: expected environment. If so, return three element list
12844: ($ownername,$ownerdomain,$ownerhome).
12845:
12846: Otherwise return the null string.
12847:
12848: If second argument 'setpriv' is true, it assigns the privileges,
12849: and returns the same three element list, unless the owner has
12850: blocked "ad hoc" Domain Coordinator access to the Author Space,
12851: in which case the null string is returned.
12852:
12853: =item *
12854:
1.243 albertel 12855: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12856: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12857: and course level
12858:
12859: =item *
12860:
1.988 raeburn 12861: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12862: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12863: $type is Course (default) or Community.
1.988 raeburn 12864: If $forcedefault evaluates to true, text returned will be default
12865: text for $type. Otherwise, if this is a course, the text returned
12866: will be a custom name for the role (if defined in the course's
12867: environment). If no custom name is defined the default is returned.
12868:
1.832 raeburn 12869: =item *
12870:
1.1172.2.23 raeburn 12871: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12872: All arguments are optional. Returns a hash of a roles, either for
12873: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12874: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12875: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12876: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12877: For each key, value is set to colon-separated start and end times for
12878: the role. If no username and domain are specified, will default to
1.934 raeburn 12879: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12880: of role statuses (active, future or previous), roles
12881: (e.g., cc,in, st etc.) and domains of the roles which can be used
12882: to restrict the list of roles reported. If no array ref is
12883: provided for types, will default to return only active roles.
1.834 albertel 12884:
1.1172.2.13 raeburn 12885: =item *
12886:
12887: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12888: user: $uname:$udom has a role in the course: $cdom_$cnum.
12889:
12890: Additional optional arguments are: $type (if role checking is to be restricted
12891: to certain user status types -- previous (expired roles), active (currently
12892: available roles) or future (roles available in the future), and
12893: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12894: have active Domain Coordinator role in course's domain or in additional
12895: domains (specified in 'Domains to check for privileged users' in course
12896: environment -- set via: Course Settings -> Classlists and staff listing).
12897:
12898: =item *
12899:
12900: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12901: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12902: $possdomains and $possroles are optional array refs -- to domains to check and
12903: roles to check. If $possdomains is not specified, a dump will be done of the
12904: users' roles.db to check for a dc or su role in any domain. This can be
12905: time consuming if &privileged is called repeatedly (e.g., when displaying a
12906: classlist), so in such cases, supplying a $possdomains array is preferred, as
12907: this then allows &privileged_by_domain() to be used, which caches the identity
12908: of privileged users, eliminating the need for repeated calls to &dump().
12909:
12910: =item *
12911:
12912: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12913: where the outer hash keys are domains specified in the $possdomains array ref,
12914: next inner hash keys are privileged roles specified in the $roles array ref,
12915: and the innermost hash contains key = value pairs for username:domain = end:start
12916: for active or future "privileged" users with that role in that domain. To avoid
12917: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12918: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12919:
1.243 albertel 12920: =back
12921:
12922: =head2 User Modification
12923:
12924: =over 4
12925:
12926: =item *
12927:
1.957 raeburn 12928: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12929: user for the level given by URL. Optional start and end dates (leave empty
12930: string or zero for "no date")
1.191 harris41 12931:
12932: =item *
12933:
1.243 albertel 12934: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12935: change a users, password, possible return values are: ok,
12936: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12937: refused
1.191 harris41 12938:
12939: =item *
12940:
1.243 albertel 12941: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12942:
12943: =item *
12944:
1.1058 raeburn 12945: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12946: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12947:
12948: will update user information (firstname,middlename,lastname,generation,
12949: permanentemail), and if forceid is true, student/employee ID also.
12950: A user's institutional affiliation(s) can also be updated.
12951: User information fields will not be overwritten with empty entries
12952: unless the field is included in the $candelete array reference.
12953: This array is included when a single user is modified via "Manage Users",
12954: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12955:
12956: =item *
12957:
1.286 matthew 12958: modifystudent
12959:
1.957 raeburn 12960: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12961: The course id is resolved based on the current user's environment.
12962: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12963: associated with a course.
12964:
1.297 matthew 12965: This call is essentially a wrapper for lonnet::modifyuser and
12966: lonnet::modify_student_enrollment
1.286 matthew 12967:
12968: Inputs:
12969:
12970: =over 4
12971:
1.957 raeburn 12972: =item B<$udom> Student's loncapa domain
1.286 matthew 12973:
1.957 raeburn 12974: =item B<$uname> Student's loncapa login name
1.286 matthew 12975:
1.964 bisitz 12976: =item B<$uid> Student/Employee ID
1.286 matthew 12977:
1.957 raeburn 12978: =item B<$umode> Student's authentication mode
1.286 matthew 12979:
1.957 raeburn 12980: =item B<$upass> Student's password
1.286 matthew 12981:
1.957 raeburn 12982: =item B<$first> Student's first name
1.286 matthew 12983:
1.957 raeburn 12984: =item B<$middle> Student's middle name
1.286 matthew 12985:
1.957 raeburn 12986: =item B<$last> Student's last name
1.286 matthew 12987:
1.957 raeburn 12988: =item B<$gene> Student's generation
1.286 matthew 12989:
1.957 raeburn 12990: =item B<$usec> Student's section in course
1.286 matthew 12991:
12992: =item B<$end> Unix time of the roles expiration
12993:
12994: =item B<$start> Unix time of the roles start date
12995:
12996: =item B<$forceid> If defined, allow $uid to be changed
12997:
12998: =item B<$desiredhome> server to use as home server for student
12999:
1.957 raeburn 13000: =item B<$email> Student's permanent e-mail address
13001:
13002: =item B<$type> Type of enrollment (auto or manual)
13003:
1.963 raeburn 13004: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13005:
13006: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13007:
1.963 raeburn 13008: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13009:
1.963 raeburn 13010: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13011:
1.1172.2.19 raeburn 13012: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13013:
13014: =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 13015:
1.286 matthew 13016: =back
1.297 matthew 13017:
13018: =item *
13019:
13020: modify_student_enrollment
13021:
1.1172.2.31 raeburn 13022: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13023: 'role.request.course' must be defined for this function to proceed.
13024:
13025: Inputs:
13026:
13027: =over 4
13028:
1.1172.2.31 raeburn 13029: =item $udom, student's domain
1.297 matthew 13030:
1.1172.2.31 raeburn 13031: =item $uname, student's name
1.297 matthew 13032:
1.1172.2.31 raeburn 13033: =item $uid, student's user id
1.297 matthew 13034:
1.1172.2.31 raeburn 13035: =item $first, student's first name
1.297 matthew 13036:
13037: =item $middle
13038:
13039: =item $last
13040:
13041: =item $gene
13042:
13043: =item $usec
13044:
13045: =item $end
13046:
13047: =item $start
13048:
1.957 raeburn 13049: =item $type
13050:
13051: =item $locktype
13052:
13053: =item $cid
13054:
13055: =item $selfenroll
13056:
13057: =item $context
13058:
1.1172.2.19 raeburn 13059: =item $credits, number of credits student will earn from this class
13060:
1.297 matthew 13061: =back
13062:
1.191 harris41 13063:
13064: =item *
13065:
1.243 albertel 13066: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13067: custom role; give a custom role to a user for the level given by URL. Specify
13068: name and domain of role author, and role name
1.191 harris41 13069:
13070: =item *
13071:
1.243 albertel 13072: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13073:
13074: =item *
13075:
1.243 albertel 13076: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13077:
13078: =back
13079:
13080: =head2 Course Infomation
13081:
13082: =over 4
1.191 harris41 13083:
13084: =item *
13085:
1.1118 foxr 13086: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13087: specified course id, including all environment settings for the
13088: course, the description of the course will be in the hash under the
13089: key 'description'
1.191 harris41 13090:
1.1118 foxr 13091: $options is an optional parameter that if supplied is a hash reference that controls
13092: what how this function works. It has the following key/values:
13093:
13094: =over 4
13095:
13096: =item freshen_cache
13097:
13098: If defined, and the environment cache for the course is valid, it is
13099: returned in the returned hash.
13100:
13101: =item one_time
13102:
13103: If defined, the last cache time is set to _now_
13104:
13105: =item user
13106:
13107: If defined, the supplied username is used instead of the current user.
13108:
13109:
13110: =back
13111:
1.191 harris41 13112: =item *
13113:
1.624 albertel 13114: resdata($name,$domain,$type,@which) : request for current parameter
13115: setting for a specific $type, where $type is either 'course' or 'user',
13116: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13117: answers for 10 minutes.
1.243 albertel 13118:
1.877 foxr 13119: =item *
13120:
13121: get_courseresdata($courseid, $domain) : dump the entire course resource
13122: data base, returning a hash that is keyed by the resource name and has
13123: values that are the resource value. I believe that the timestamps and
13124: versions are also returned.
13125:
1.1172.2.31 raeburn 13126: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13127: supplemental content area. This routine caches the number of files for
13128: 10 minutes.
13129:
1.243 albertel 13130: =back
13131:
13132: =head2 Course Modification
13133:
13134: =over 4
1.191 harris41 13135:
13136: =item *
13137:
1.243 albertel 13138: writecoursepref($courseid,%prefs) : write preferences (environment
13139: database) for a course
1.191 harris41 13140:
13141: =item *
13142:
1.1011 raeburn 13143: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13144:
13145: =item *
13146:
1.1038 raeburn 13147: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13148:
1.1167 droeschl 13149: =item *
13150:
13151: is_course($courseid), is_course($cdom, $cnum)
13152:
13153: Accepts either a combined $courseid (in the form of domain_courseid) or the
13154: two component version $cdom, $cnum. It checks if the specified course exists.
13155:
13156: Returns:
13157: undef if the course doesn't exist, otherwise
13158: in scalar context the combined courseid.
13159: in list context the two components of the course identifier, domain and
13160: courseid.
13161:
1.243 albertel 13162: =back
13163:
13164: =head2 Resource Subroutines
13165:
13166: =over 4
1.191 harris41 13167:
13168: =item *
13169:
1.243 albertel 13170: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13171:
13172: =item *
13173:
1.243 albertel 13174: repcopy($filename) : subscribes to the requested file, and attempts to
13175: replicate from the owning library server, Might return
1.607 raeburn 13176: 'unavailable', 'not_found', 'forbidden', 'ok', or
13177: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13178: resource. Expects the local filesystem pathname
13179: (/home/httpd/html/res/....)
13180:
13181: =back
13182:
13183: =head2 Resource Information
13184:
13185: =over 4
1.191 harris41 13186:
13187: =item *
13188:
1.1172.2.28 raeburn 13189: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13190: and returns the value of a variety of different possible values,
13191: $varname should be a request string, and the other parameters can be
13192: used to specify who and what one is asking about. Ordinarily, $cid
13193: does not need to be specified, as it is retrived from
13194: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13195: within lonuserstate::loadmap() when initializing a course, before
13196: $env{'request.course.id'} has been set, so it needs to be provided
13197: in that one case.
1.243 albertel 13198:
13199: Possible values for $varname are environment.lastname (or other item
13200: from the envirnment hash), user.name (or someother aspect about the
13201: user), resource.0.maxtries (or some other part and parameter of a
13202: resource)
1.204 albertel 13203:
13204: =item *
13205:
1.243 albertel 13206: directcondval($number) : get current value of a condition; reads from a state
13207: string
1.204 albertel 13208:
13209: =item *
13210:
1.243 albertel 13211: condval($condidx) : value of condition index based on state
1.204 albertel 13212:
13213: =item *
13214:
1.243 albertel 13215: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13216: resource's metadata, $what should be either a specific key, or either
13217: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13218: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13219:
13220: this function automatically caches all requests
1.191 harris41 13221:
13222: =item *
13223:
1.243 albertel 13224: metadata_query($query,$custom,$customshow) : make a metadata query against the
13225: network of library servers; returns file handle of where SQL and regex results
13226: will be stored for query
1.191 harris41 13227:
13228: =item *
13229:
1.243 albertel 13230: symbread($filename) : return symbolic list entry (filename argument optional);
13231: returns the data handle
1.191 harris41 13232:
13233: =item *
13234:
1.1172.2.17 raeburn 13235: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13236: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13237: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13238: on failure, user must be in a course, as it assumes the existence of
13239: the course initial hash, and uses $env('request.course.id'}. The third
13240: arg is an optional reference to a scalar. If this arg is passed in the
13241: call to symbverify, it will be set to 1 if the symb has been set to be
13242: encrypted; otherwise it will be null.
1.243 albertel 13243:
1.191 harris41 13244: =item *
13245:
1.243 albertel 13246: symbclean($symb) : removes versions numbers from a symb, returns the
13247: cleaned symb
1.191 harris41 13248:
13249: =item *
13250:
1.243 albertel 13251: is_on_map($uri) : checks if the $uri is somewhere on the current
13252: course map, user must be in a course for it to work.
1.191 harris41 13253:
13254: =item *
13255:
1.243 albertel 13256: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13257:
13258: =item *
13259:
1.243 albertel 13260: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13261: a random seed, all arguments are optional, if they aren't sent it uses the
13262: environment to derive them. Note: if symb isn't sent and it can't get one
13263: from &symbread it will use the current time as its return value
1.191 harris41 13264:
13265: =item *
13266:
1.243 albertel 13267: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13268: unfakeable, receipt
1.191 harris41 13269:
13270: =item *
13271:
1.620 albertel 13272: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13273:
13274: =item *
13275:
1.243 albertel 13276: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13277:
13278: =item *
13279:
1.243 albertel 13280: 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 13281:
13282: =item *
13283:
1.243 albertel 13284: 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 13285:
13286: =item *
13287:
1.243 albertel 13288: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13289:
13290: =item *
13291:
1.243 albertel 13292: devalidate($symb) : devalidate temporary spreadsheet calculations,
13293: forcing spreadsheet to reevaluate the resource scores next time.
13294:
1.1172.2.13 raeburn 13295: =item *
13296:
13297: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13298: when viewing in course context.
13299:
13300: input: six args -- filename (decluttered), course number, course domain,
13301: url, symb (if registered) and group (if this is a
13302: group item -- e.g., bulletin board, group page etc.).
13303:
13304: output: array of five scalars --
13305: $cfile -- url for file editing if editable on current server
13306: $home -- homeserver of resource (i.e., for author if published,
13307: or course if uploaded.).
13308: $switchserver -- 1 if server switch will be needed.
13309: $forceedit -- 1 if icon/link should be to go to edit mode
13310: $forceview -- 1 if icon/link should be to go to view mode
13311:
13312: =item *
13313:
13314: is_course_upload($file,$cnum,$cdom)
13315:
13316: Used in course context to determine if current file was uploaded to
13317: the course (i.e., would be found in /userfiles/docs on the course's
13318: homeserver.
13319:
13320: input: 3 args -- filename (decluttered), course number and course domain.
13321: output: boolean -- 1 if file was uploaded.
13322:
1.243 albertel 13323: =back
13324:
13325: =head2 Storing/Retreiving Data
13326:
13327: =over 4
1.191 harris41 13328:
13329: =item *
13330:
1.243 albertel 13331: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13332: for this url; hashref needs to be given and should be a \%hashname; the
13333: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13334: be derived from the env
1.191 harris41 13335:
13336: =item *
13337:
1.243 albertel 13338: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13339: uses critical subroutine
1.191 harris41 13340:
13341: =item *
13342:
1.243 albertel 13343: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13344: all args are optional
1.191 harris41 13345:
13346: =item *
13347:
1.717 albertel 13348: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13349: dumps the complete (or key matching regexp) namespace into a hash
13350: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13351: normally &store()ed into
13352:
13353: $range should be either an integer '100' (give me the first 100
13354: matching records)
13355: or be two integers sperated by a - with no spaces
13356: '30-50' (give me the 30th through the 50th matching
13357: records)
13358:
13359:
13360: =item *
13361:
1.1172.2.59 raeburn 13362: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13363: replaces a &store() version of data with a replacement set of data
13364: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13365: reference. If $tolog is true, the transaction is logged in the courselog
13366: with an action=PUTSTORE.
1.717 albertel 13367:
13368: =item *
13369:
1.243 albertel 13370: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13371: works very similar to store/cstore, but all data is stored in a
13372: temporary location and can be reset using tmpreset, $storehash should
13373: be a hash reference, returns nothing on success
1.191 harris41 13374:
13375: =item *
13376:
1.243 albertel 13377: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13378: similar to restore, but all data is stored in a temporary location and
13379: can be reset using tmpreset. Returns a hash of values on success,
13380: error string otherwise.
1.191 harris41 13381:
13382: =item *
13383:
1.243 albertel 13384: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13385: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13386:
13387: =item *
13388:
1.243 albertel 13389: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13390: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13391:
13392: =item *
13393:
1.243 albertel 13394: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13395: namesp ($udom and $uname are optional)
1.191 harris41 13396:
13397: =item *
13398:
1.702 albertel 13399: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13400: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13401: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13402:
1.702 albertel 13403: $range should be either an integer '100' (give me the first 100
13404: matching records)
13405: or be two integers sperated by a - with no spaces
13406: '30-50' (give me the 30th through the 50th matching
13407: records)
1.449 matthew 13408: =item *
13409:
13410: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13411: $store can be a scalar, an array reference, or if the amount to be
13412: incremented is > 1, a hash reference.
13413:
13414: ($udom and $uname are optional)
1.191 harris41 13415:
13416: =item *
13417:
1.243 albertel 13418: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13419: ($udom and $uname are optional)
1.191 harris41 13420:
13421: =item *
13422:
1.243 albertel 13423: cput($namespace,$storehash,$udom,$uname) : critical put
13424: ($udom and $uname are optional)
1.191 harris41 13425:
13426: =item *
13427:
1.748 albertel 13428: newput($namespace,$storehash,$udom,$uname) :
13429:
13430: Attempts to store the items in the $storehash, but only if they don't
13431: currently exist, if this succeeds you can be certain that you have
13432: successfully created a new key value pair in the $namespace db.
13433:
13434:
13435: Args:
13436: $namespace: name of database to store values to
13437: $storehash: hashref to store to the db
13438: $udom: (optional) domain of user containing the db
13439: $uname: (optional) name of user caontaining the db
13440:
13441: Returns:
13442: 'ok' -> succeeded in storing all keys of $storehash
13443: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13444: least <key> already existed in the db (other
13445: requested keys may also already exist)
1.967 bisitz 13446: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13447: 'con_lost' -> unable to contact request server
13448: 'refused' -> action was not allowed by remote machine
13449:
13450:
13451: =item *
13452:
1.243 albertel 13453: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13454: reference filled in from namesp (encrypts the return communication)
13455: ($udom and $uname are optional)
1.191 harris41 13456:
13457: =item *
13458:
1.243 albertel 13459: log($udom,$name,$home,$message) : write to permanent log for user; use
13460: critical subroutine
13461:
1.806 raeburn 13462: =item *
13463:
1.860 raeburn 13464: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13465: array reference filled in from namespace found in domain level on either
13466: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13467:
13468: =item *
13469:
1.860 raeburn 13470: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13471: domain level either on specified domain server ($uhome) or primary domain
13472: server ($udom and $uhome are optional)
1.806 raeburn 13473:
1.943 raeburn 13474: =item *
13475:
1.1172.2.35 raeburn 13476: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13477: for: authentication, language, quotas, timezone, date locale, and portal URL in
13478: the target domain.
13479:
13480: May also include additional key => value pairs for the following groups:
13481:
13482: =over
13483:
13484: =item
13485: disk quotas (MB allocated by default to portfolios and authoring spaces).
13486:
13487: =over
13488:
13489: =item defaultquota, authorquota
13490:
13491: =back
13492:
13493: =item
13494: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13495: portfolio for users).
13496:
13497: =over
13498:
13499: =item
13500: aboutme, blog, webdav, portfolio
13501:
13502: =back
13503:
13504: =item
13505: requestcourses: ability to request courses, and how requests are processed.
13506:
13507: =over
13508:
13509: =item
1.1172.2.37 raeburn 13510: official, unofficial, community, textbook
1.1172.2.35 raeburn 13511:
13512: =back
13513:
13514: =item
13515: inststatus: types of institutional affiliation, and order in which they are displayed.
13516:
13517: =over
13518:
13519: =item
1.1172.2.44 raeburn 13520: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13521:
13522: =back
13523:
13524: =item
13525: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13526: for course's uploaded content.
13527:
13528: =over
13529:
13530: =item
1.1172.2.37 raeburn 13531: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13532:
13533: =back
13534:
13535: =item
13536: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13537: on your servers.
13538:
13539: =over
13540:
13541: =item
13542: remotesessions, hostedsessions
13543:
13544: =back
13545:
13546: =back
13547:
13548: In cases where a domain coordinator has never used the "Set Domain Configuration"
13549: utility to create a configuration.db file on a domain's primary library server
13550: only the following domain defaults: auth_def, auth_arg_def, lang_def
13551: -- corresponding values are authentication type (internal, krb4, krb5,
13552: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13553: will be available. Values are retrieved from cache (if current), unless the
13554: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13555: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13556:
13557: Typical usage:
1.943 raeburn 13558:
1.1172.2.35 raeburn 13559: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13560:
1.243 albertel 13561: =back
13562:
13563: =head2 Network Status Functions
13564:
13565: =over 4
1.191 harris41 13566:
13567: =item *
13568:
1.1137 raeburn 13569: dirlist() : return directory list based on URI (first arg).
13570:
13571: Inputs: 1 required, 5 optional.
13572:
13573: =over
13574:
13575: =item
13576: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13577:
13578: =item
13579: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13580:
13581: =item
13582: $username - username of user/course to be listed. Extracted from $uri if absent.
13583:
13584: =item
13585: $getpropath - boolean: 1 if prepend path using &propath().
13586:
13587: =item
13588: $getuserdir - boolean: 1 if prepend path for "userfiles".
13589:
13590: =item
13591: $alternateRoot - path to prepend in place of path from $uri.
13592:
13593: =back
13594:
13595: Returns: Array of up to two items.
13596:
13597: =over
13598:
13599: a reference to an array of files/subdirectories
13600:
13601: =over
13602:
13603: Each element in the array of files/subdirectories is a & separated list of
13604: item name and the result of running stat on the item. If dirlist was requested
13605: for a file instead of a directory, the item name will be ''. For a directory
13606: listing, if the item is a metadata file, the element will end &N&M
13607: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13608: default copyright set (1).
13609:
13610: =back
13611:
13612: a scalar containing error condition (if encountered).
13613:
13614: =over
13615:
13616: =item
13617: no_host (no homeserver identified for $username:$domain).
13618:
13619: =item
13620: no_such_host (server contacted for listing not identified as valid host).
13621:
13622: =item
13623: con_lost (connection to remote server failed).
13624:
13625: =item
13626: refused (invalid $username:$domain received on lond side).
13627:
13628: =item
13629: no_such_dir (directory at specified path on lond side does not exist).
13630:
13631: =item
13632: empty (directory at specified path on lond side is empty).
13633:
13634: =over
13635:
13636: This is currently not encountered because the &ls3, &ls2,
13637: &ls (_handler) routines on the lond side do not filter out
13638: . and .. from a directory listing.
13639:
13640: =back
13641:
13642: =back
13643:
13644: =back
1.191 harris41 13645:
13646: =item *
13647:
1.243 albertel 13648: spareserver() : find server with least workload from spare.tab
13649:
1.986 foxr 13650:
13651: =item *
13652:
13653: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13654: if there is no corresponding loncapa host.
13655:
1.243 albertel 13656: =back
13657:
1.986 foxr 13658:
1.243 albertel 13659: =head2 Apache Request
13660:
13661: =over 4
1.191 harris41 13662:
13663: =item *
13664:
1.243 albertel 13665: ssi($url,%hash) : server side include, does a complete request cycle on url to
13666: localhost, posts hash
13667:
13668: =back
13669:
13670: =head2 Data to String to Data
13671:
13672: =over 4
1.191 harris41 13673:
13674: =item *
13675:
1.243 albertel 13676: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13677: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13678:
13679: =item *
13680:
1.243 albertel 13681: hashref2str($hashref) : convert a hashref into a string complete with
13682: escaping and '=' and '&' separators, supports elements that are
13683: arrayrefs and hashrefs
1.191 harris41 13684:
13685: =item *
13686:
1.243 albertel 13687: arrayref2str($arrayref) : convert an arrayref into a string complete
13688: with escaping and '&' separators, supports elements that are arrayrefs
13689: and hashrefs
1.191 harris41 13690:
13691: =item *
13692:
1.243 albertel 13693: str2hash($string) : convert string to hash using unescaping and
13694: splitting on '=' and '&', supports elements that are arrayrefs and
13695: hashrefs
1.191 harris41 13696:
13697: =item *
13698:
1.243 albertel 13699: str2array($string) : convert string to hash using unescaping and
13700: splitting on '&', supports elements that are arrayrefs and hashrefs
13701:
13702: =back
13703:
13704: =head2 Logging Routines
13705:
13706:
13707: These routines allow one to make log messages in the lonnet.log and
13708: lonnet.perm logfiles.
1.191 harris41 13709:
1.1119 foxr 13710: =over 4
13711:
1.191 harris41 13712: =item *
13713:
1.243 albertel 13714: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13715:
13716: =item *
13717:
1.243 albertel 13718: logthis() : append message to the normal lonnet.log file, it gets
13719: preiodically rolled over and deleted.
1.191 harris41 13720:
13721: =item *
13722:
1.243 albertel 13723: logperm() : append a permanent message to lonnet.perm.log, this log
13724: file never gets deleted by any automated portion of the system, only
13725: messages of critical importance should go in here.
13726:
1.1119 foxr 13727:
1.243 albertel 13728: =back
13729:
13730: =head2 General File Helper Routines
13731:
13732: =over 4
1.191 harris41 13733:
13734: =item *
13735:
1.481 raeburn 13736: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13737: (a) files in /uploaded
13738: (i) If a local copy of the file exists -
13739: compares modification date of local copy with last-modified date for
13740: definitive version stored on home server for course. If local copy is
13741: stale, requests a new version from the home server and stores it.
13742: If the original has been removed from the home server, then local copy
13743: is unlinked.
13744: (ii) If local copy does not exist -
13745: requests the file from the home server and stores it.
13746:
13747: If $caller is 'uploadrep':
13748: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13749: for request for files originally uploaded via DOCS.
13750: - returns 'ok' if fresh local copy now available, -1 otherwise.
13751:
13752: Otherwise:
13753: This indicates a call from the content generation phase of the request.
13754: - returns the entire contents of the file or -1.
13755:
13756: (b) files in /res
13757: - returns the entire contents of a file or -1;
13758: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13759:
1.712 albertel 13760:
13761: =item *
13762:
13763: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13764: reference
13765:
13766: returns either a stat() list of data about the file or an empty list
13767: if the file doesn't exist or couldn't find out about it (connection
13768: problems or user unknown)
13769:
1.191 harris41 13770: =item *
13771:
1.243 albertel 13772: filelocation($dir,$file) : returns file system location of a file
13773: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13774: directory that relative $file lookups are to looked in ($dir of /a/dir
13775: and a file of ../bob will become /a/bob)
1.191 harris41 13776:
13777: =item *
13778:
13779: hreflocation($dir,$file) : returns file system location or a URL; same as
13780: filelocation except for hrefs
13781:
13782: =item *
13783:
1.1172.2.49 raeburn 13784: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13785: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13786:
1.243 albertel 13787: =back
13788:
1.608 albertel 13789: =head2 Usererfile file routines (/uploaded*)
13790:
13791: =over 4
13792:
13793: =item *
13794:
13795: userfileupload(): main rotine for putting a file in a user or course's
13796: filespace, arguments are,
13797:
1.620 albertel 13798: formname - required - this is the name of the element in $env where the
1.608 albertel 13799: filename, and the contents of the file to create/modifed exist
1.620 albertel 13800: the filename is in $env{'form.'.$formname.'.filename'} and the
13801: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13802: context - if coursedoc, store the file in the course of the active role
13803: of the current user;
13804: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13805: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13806: subdir - required - subdirectory to put the file in under ../userfiles/
13807: if undefined, it will be placed in "unknown"
13808:
13809: (This routine calls clean_filename() to remove any dangerous
13810: characters from the filename, and then calls finuserfileupload() to
13811: complete the transaction)
13812:
13813: returns either the url of the uploaded file (/uploaded/....) if successful
13814: and /adm/notfound.html if unsuccessful
13815:
13816: =item *
13817:
13818: clean_filename(): routine for cleaing a filename up for storage in
13819: userfile space, argument is:
13820:
13821: filename - proposed filename
13822:
13823: returns: the new clean filename
13824:
13825: =item *
13826:
1.1090 raeburn 13827: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13828: userspace, probably shouldn't be called directly
13829:
13830: docuname: username or courseid of destination for the file
13831: docudom: domain of user/course of destination for the file
13832: formname: same as for userfileupload()
1.1090 raeburn 13833: fname: filename (including subdirectories) for the file
13834: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13835: allfiles: reference to hash used to store objects found by parser
13836: codebase: reference to hash used for codebases of java objects found by parser
13837: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13838: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13839: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13840: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13841: context: if 'overwrite', will move the uploaded file from its temporary location to
13842: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13843: mimetype: reference to scalar to accommodate mime type determined
13844: from File::MMagic if $parser = parse.
1.608 albertel 13845:
13846: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13847: and /adm/notfound.html if unsuccessful (or an error message if context
13848: was 'overwrite').
13849:
1.608 albertel 13850:
13851: =item *
13852:
13853: renameuserfile(): renames an existing userfile to a new name
13854:
13855: Args:
13856: docuname: username or courseid of destination for the file
13857: docudom: domain of user/course of destination for the file
13858: old: current file name (including any subdirs under userfiles)
13859: new: desired file name (including any subdirs under userfiles)
13860:
13861: =item *
13862:
13863: mkdiruserfile(): creates a directory is a userfiles dir
13864:
13865: Args:
13866: docuname: username or courseid of destination for the file
13867: docudom: domain of user/course of destination for the file
13868: dir: dir to create (including any subdirs under userfiles)
13869:
13870: =item *
13871:
13872: removeuserfile(): removes a file that exists in userfiles
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: fname: filname to delete (including any subdirs under userfiles)
13878:
13879: =item *
13880:
13881: removeuploadedurl(): convience function for removeuserfile()
13882:
13883: Args:
13884: url: a full /uploaded/... url to delete
13885:
1.747 albertel 13886: =item *
13887:
13888: get_portfile_permissions():
13889: Args:
13890: domain: domain of user or course contain the portfolio files
13891: user: name of user or num of course contain the portfolio files
13892: Returns:
13893: hashref of a dump of the proper file_permissions.db
13894:
13895:
13896: =item *
13897:
13898: get_access_controls():
13899:
13900: Args:
13901: current_permissions: the hash ref returned from get_portfile_permissions()
13902: group: (optional) the group you want the files associated with
13903: file: (optional) the file you want access info on
13904:
13905: Returns:
1.749 raeburn 13906: a hash (keys are file names) of hashes containing
13907: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13908: values are XML containing access control settings (see below)
1.747 albertel 13909:
13910: Internal notes:
13911:
1.749 raeburn 13912: access controls are stored in file_permissions.db as key=value pairs.
13913: key -> path to file/file_name\0uniqueID:scope_end_start
13914: where scope -> public,guest,course,group,domains or users.
13915: end -> UNIX time for end of access (0 -> no end date)
13916: start -> UNIX time for start of access
13917:
13918: value -> XML description of access control
13919: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13920: <start></start>
13921: <end></end>
13922:
13923: <password></password> for scope type = guest
13924:
13925: <domain></domain> for scope type = course or group
13926: <number></number>
13927: <roles id="">
13928: <role></role>
13929: <access></access>
13930: <section></section>
13931: <group></group>
13932: </roles>
13933:
13934: <dom></dom> for scope type = domains
13935:
13936: <users> for scope type = users
13937: <user>
13938: <uname></uname>
13939: <udom></udom>
13940: </user>
13941: </users>
13942: </scope>
13943:
13944: Access data is also aggregated for each file in an additional key=value pair:
13945: key -> path to file/file_name\0accesscontrol
13946: value -> reference to hash
13947: hash contains key = value pairs
13948: where key = uniqueID:scope_end_start
13949: value = UNIX time record was last updated
13950:
13951: Used to improve speed of look-ups of access controls for each file.
13952:
13953: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13954:
1.1172.2.13 raeburn 13955: =item *
13956:
1.749 raeburn 13957: modify_access_controls():
13958:
13959: Modifies access controls for a portfolio file
13960: Args
13961: 1. file name
13962: 2. reference to hash of required changes,
13963: 3. domain
13964: 4. username
13965: where domain,username are the domain of the portfolio owner
13966: (either a user or a course)
13967:
13968: Returns:
13969: 1. result of additions or updates ('ok' or 'error', with error message).
13970: 2. result of deletions ('ok' or 'error', with error message).
13971: 3. reference to hash of any new or updated access controls.
13972: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13973: key = integer (inbound ID)
1.1172.2.13 raeburn 13974: value = uniqueID
13975:
13976: =item *
13977:
13978: get_timebased_id():
13979:
13980: Attempts to get a unique timestamp-based suffix for use with items added to a
13981: course via the Course Editor (e.g., folders, composite pages,
13982: group bulletin boards).
13983:
13984: Args: (first three required; six others optional)
13985:
13986: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13987: docssequence, or name of group
13988:
13989: 2. keyid (alphanumeric): name of temporary locking key in hash,
13990: e.g., num, boardids
13991:
13992: 3. namespace: name of gdbm file used to store suffixes already assigned;
13993: file will be named nohist_namespace.db
13994:
13995: 4. cdom: domain of course; default is current course domain from %env
13996:
13997: 5. cnum: course number; default is current course number from %env
13998:
13999: 6. idtype: set to concat if an additional digit is to be appended to the
14000: unix timestamp to form the suffix, if the plain timestamp is already
14001: in use. Default is to not do this, but simply increment the unix
14002: timestamp by 1 until a unique key is obtained.
14003:
14004: 7. who: holder of locking key; defaults to user:domain for user.
14005:
14006: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14007: retrying); default is 3.
14008:
14009: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14010:
14011: Returns:
14012:
14013: 1. suffix obtained (numeric)
14014:
14015: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14016:
14017: 3. error: contains (localized) error message if an error occurred.
14018:
1.747 albertel 14019:
1.608 albertel 14020: =back
14021:
1.243 albertel 14022: =head2 HTTP Helper Routines
14023:
14024: =over 4
14025:
1.191 harris41 14026: =item *
14027:
14028: escape() : unpack non-word characters into CGI-compatible hex codes
14029:
14030: =item *
14031:
14032: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14033:
1.243 albertel 14034: =back
14035:
14036: =head1 PRIVATE SUBROUTINES
14037:
14038: =head2 Underlying communication routines (Shouldn't call)
14039:
14040: =over 4
14041:
14042: =item *
14043:
14044: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14045:
14046: =item *
14047:
14048: reply() : uses subreply to send a message to remote machine, logs all failures
14049:
14050: =item *
14051:
14052: critical() : passes a critical message to another server; if cannot
14053: get through then place message in connection buffer directory and
14054: returns con_delayed, if incapable of saving message, returns
14055: con_failed
14056:
14057: =item *
14058:
14059: reconlonc() : tries to reconnect lonc client processes.
14060:
14061: =back
14062:
14063: =head2 Resource Access Logging
14064:
14065: =over 4
14066:
14067: =item *
14068:
14069: flushcourselogs() : flush (save) buffer logs and access logs
14070:
14071: =item *
14072:
14073: courselog($what) : save message for course in hash
14074:
14075: =item *
14076:
14077: courseacclog($what) : save message for course using &courselog(). Perform
14078: special processing for specific resource types (problems, exams, quizzes, etc).
14079:
1.191 harris41 14080: =item *
14081:
14082: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14083: as a PerlChildExitHandler
1.243 albertel 14084:
14085: =back
14086:
14087: =head2 Other
14088:
14089: =over 4
14090:
14091: =item *
14092:
14093: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14094:
14095: =back
14096:
14097: =cut
1.877 foxr 14098:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>